Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(ingest): add BigQuery connector (#1626)
Sameer Kadamc208c230ca12
diff --git a/docs/docs.json b/docs/docs.jsonindex c5bb271b..f36fffa5 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -107,6 +107,7 @@"integrations/docling","integrations/snowflake","integrations/databricks",+ "integrations/bigquery","integrations/salesforce","integrations/redshift","integrations/powerbi"diff --git a/docs/integrations/bigquery.md b/docs/integrations/bigquery.mdnew file mode 100644index 00000000..b5890034--- /dev/null+++ b/docs/integrations/bigquery.md@@ -0,0 +1,357 @@+---+title: "BigQuery Integration"+description: "Ingest structured data from Google BigQuery tables and queries into Semantica's KG pipeline."+icon: "google"+---++> Extract data from BigQuery tables, queries, and schemas into Semantica with Application Default Credentials or service-account key-file authentication.+++## Installation++```bash+# Install with BigQuery support+pip install "semantica[db-bigquery]"++# Or install the connector separately+pip install google-cloud-bigquery>=3.0.0+```+++## Basic Usage++```python+import os+from semantica.ingest import BigQueryIngestor++ingestor = BigQueryIngestor(+ project=os.getenv("BIGQUERY_PROJECT"),+ dataset=os.getenv("BIGQUERY_DATASET"),+)++data = ingestor.ingest_table("orders", limit=1000)+print(f"Retrieved {data.row_count} rows, columns: {data.columns}")+```++<Tip>+Use environment variables (or a `.env` file with `python-dotenv`) to keep configuration out of source code. `BigQueryIngestor()` with no arguments reads from `BIGQUERY_*` environment variables automatically, once `BIGQUERY_PROJECT` is set.+</Tip>+++## Authentication++<Tabs>+ <Tab title="Application Default Credentials (Recommended)">+ ```python+ import os+ from semantica.ingest import BigQueryIngestor++ ingestor = BigQueryIngestor(+ project=os.getenv("BIGQUERY_PROJECT"),+ dataset=os.getenv("BIGQUERY_DATASET"),+ )+ ```++ Set `BIGQUERY_PROJECT` and optionally `BIGQUERY_DATASET` in your environment:++ ```bash+ export BIGQUERY_PROJECT="my-gcp-project"+ export BIGQUERY_DATASET="my_dataset"+ ```++ ADC resolves credentials automatically from the environment, in this order:+ 1. `GOOGLE_APPLICATION_CREDENTIALS` environment variable (path to a key file)+ 2. gcloud default credentials (`gcloud auth application-default login`)+ 3. Attached service account (GKE, Cloud Run, Vertex AI, Compute Engine)++ For local development:++ ```bash+ gcloud auth application-default login+ ```++ No credential file is needed in production when the workload identity is+ attached to a service account.+ </Tab>+ <Tab title="Service Account Key File">+ ```python+ import os+ from semantica.ingest import BigQueryIngestor++ ingestor = BigQueryIngestor(+ project=os.getenv("BIGQUERY_PROJECT"),+ dataset=os.getenv("BIGQUERY_DATASET"),+ credentials_file=os.getenv("BIGQUERY_CREDENTIALS_FILE"),+ )+ ```++ ```bash+ export BIGQUERY_PROJECT="my-gcp-project"+ export BIGQUERY_DATASET="my_dataset"+ export BIGQUERY_CREDENTIALS_FILE="/run/secrets/sa-key.json"+ ```++ Download a JSON key file from the GCP console under+ **IAM & Admin → Service Accounts → [your service account] → Keys**.+ Store it outside version control and inject it via a secret manager or+ mounted volume.++ The service account requires at minimum the **BigQuery Data Viewer**+ (`roles/bigquery.dataViewer`) and **BigQuery Job User**+ (`roles/bigquery.jobUser`) roles on the project.+ </Tab>+</Tabs>+++## Environment Variables++All constructor parameters have environment-variable fallbacks:++| Variable | Parameter | Default |+|---|---|---|+| `BIGQUERY_PROJECT` | `project` | — (required) |+| `BIGQUERY_DATASET` | `dataset` | — |+| `BIGQUERY_LOCATION` | `location` | project default |+| `BIGQUERY_CREDENTIALS_FILE` | `credentials_file` | ADC |+++## Table Ingestion++### Ingest a table with filters++```python+data = ingestor.ingest_table(+ "orders",+ where="status = 'shipped' AND created_date >= '2024-01-01'",+ order_by="created_date DESC",+ limit=50000,+)+print(f"Fetched {data.row_count} rows from {data.table_name}")+```++<Warning>+`where` and `order_by` accept raw SQL fragments. They are validated against+a blocklist (statement separators, UNION, DML/DDL keywords, comment sequences)+but are intended for trusted, operator-controlled input. Do not pass raw+end-user text directly to these parameters.+</Warning>++### Override project and dataset per call++```python+data = ingestor.ingest_table(+ "transactions",+ project="analytics-project-456",+ dataset="finance",+ limit=10000,+)+```++### Ingest from a fully-qualified table++```python+# project and dataset on the ingestor default to the connector's values;+# you can override them at the call site for cross-project queries.+data = ingestor.ingest_table(+ "daily_sales",+ project="reporting-project",+ dataset="warehouse",+)+```+++## Custom SQL Queries++```python+data = ingestor.ingest_query("""+ SELECT+ customer_id,+ SUM(amount) AS total_amount,+ COUNT(*) AS order_count+ FROM `my-project`.`sales`.`orders`+ WHERE DATE(created_at) >= '2024-01-01'+ GROUP BY customer_id+ ORDER BY total_amount DESC+ LIMIT 1000+""")+print(f"Query returned {data.row_count} rows")+```++The query string is passed verbatim to BigQuery. The caller is responsible for+correctness and safety of the SQL.++### Parameterised queries++```python+from google.cloud import bigquery++job_config = bigquery.QueryJobConfig(+ query_parameters=[+ bigquery.ScalarQueryParameter("min_amount", "FLOAT64", 100.0),+ ]+)++data = ingestor.ingest_query(+ "SELECT id, amount FROM `my-project`.`sales`.`orders` WHERE amount >= @min_amount",+ job_config=job_config,+)+```+++## Schema Inspection++```python+# Inspect columns for a table+schema = ingestor.get_table_schema("orders")++print(f"Row count: {schema['num_rows']}")+print(f"Clustering fields: {schema['clustering_fields']}")+for col in schema["columns"]:+ nullable = "NULLABLE" if col["nullable"] else "REQUIRED"+ print(f" {col['name']}: {col['type']} ({nullable})")+```++### List tables in a dataset++```python+tables = ingestor.list_tables()+print(f"Tables in dataset: {tables}")+# ['customers', 'orders', 'products', 'returns']++# Or specify a different dataset+tables = ingestor.list_tables(dataset="analytics", project="my-other-project")+```+++## Export as Semantica Documents++Convert ingested rows to the Semantica document format for use with+`GraphBuilder`:++```python+documents = ingestor.export_as_documents(+ data,+ id_field="order_id", # field to use as document ID+ text_fields=["customer_name", "product_name", "notes"],+)++print(f"Created {len(documents)} documents")+# Each document:+# {+# "id": "ORD-12345",+# "text": "Alice Smith Widget Pro Shipped on time",+# "metadata": {+# "source": "bigquery",+# "table": "orders",+# "project": "my-gcp-project",+# "dataset": "sales",+# "location": "US",+# "row_data": { ... full original row ... }+# }+# }+```++Feed the documents directly into `GraphBuilder`:++```python+from semantica.kg import GraphBuilder++builder = GraphBuilder()+kg = builder.build(documents)+```++When `text_fields` is omitted, all `str`-typed column values in each row are+joined to form the document text. Integer, float, Decimal, and `None` values+are excluded from the default text composition.+++## Context Manager++Prefer the context manager for batches of queries — it opens one client on+entry and closes it on exit, so every call inside the `with` block reuses the+same authenticated session:++```python+import os+from semantica.ingest import BigQueryIngestor++with BigQueryIngestor(+ project=os.getenv("BIGQUERY_PROJECT"),+ dataset=os.getenv("BIGQUERY_DATASET"),+) as bq:+ orders = bq.ingest_table("orders", limit=10000)+ customers = bq.ingest_table("customers", limit=5000)+ tables = bq.list_tables()+ schema = bq.get_table_schema("orders")+```++Outside a context manager each method call opens and closes a transient+client independently.+++## Connection Testing++```python+import os+from semantica.ingest import BigQueryConnector++connector = BigQueryConnector(+ project=os.getenv("BIGQUERY_PROJECT"),+)+if connector.test_connection():+ print("Connected to BigQuery successfully.")+else:+ print("Connection failed — check project ID and credentials.")+```+++## Troubleshooting++**`ImportError: BigQuery ingestion requires optional dependency 'google-cloud-bigquery'`**++Install the optional extra:++```bash+pip install "semantica[db-bigquery]"+```++**`google.auth.exceptions.DefaultCredentialsError`**++No credentials were found in the environment. Either:+- Run `gcloud auth application-default login` for local development, or+- Set `GOOGLE_APPLICATION_CREDENTIALS` to the path of a service-account JSON key file, or+- Set `BIGQUERY_CREDENTIALS_FILE` to the path of a service-account JSON key file.++**`google.api_core.exceptions.Forbidden`**++The service account or user account does not have permission to access the+dataset or table. Ensure the account has at minimum:+- `roles/bigquery.dataViewer` on the dataset or project+- `roles/bigquery.jobUser` on the project++**`ValidationError: Invalid BigQuery project ID`**++Project IDs may contain letters, digits, hyphens, and underscores, and must+start with a letter. Numeric-only or leading-hyphen project IDs are rejected.++**`ValidationError: Invalid table_name`**++Table and dataset names must start with a letter or underscore and contain+only letters, digits, and underscores. Hyphens are not permitted in table or+dataset names (use underscores instead).++**Slow queries**++Use `limit` and `where` to restrict the rows fetched. For large analytical+queries, consider using `ingest_query()` with a pre-aggregated SQL statement+rather than ingesting raw table rows.+++## See Also++- [Ingest Module](../reference/ingest) — Full `BigQueryIngestor` API and all other ingestors.+- [Snowflake Integration](/integrations/snowflake) — Warehouse connector with a similar design.+- [Redshift Integration](/integrations/redshift) — AWS Redshift connector.+- [Databricks Integration](/integrations/databricks) — Lakehouse connector.+- [Installation](../installation) — All optional dependency extras.+- [Knowledge Graph](../reference/kg) — Build a KG from ingested BigQuery data.diff --git a/pyproject.toml b/pyproject.tomlindex b369bf3f..8382ffe7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -159,6 +159,7 @@ db-arrow = []db-salesforce = ["simple-salesforce>=1.12.0"]db-redshift = ["redshift-connector>=2.0.0"]+db-bigquery = ["google-cloud-bigquery>=3.0.0"]ingest-parquet = ["pyarrow>=24.0.0; python_version >= '3.10'","pyarrow>=14.0.0,<24.0.0; python_version < '3.10'"@@ -171,7 +172,7 @@ ingest-sap = ["requests>=2.28.0"]ingest-git = ["GitPython>=3.1.58"]db-all = [- "semantica[db-snowflake,db-databricks,db-salesforce,db-redshift,db-arrow]"+ "semantica[db-snowflake,db-databricks,db-salesforce,db-redshift,db-bigquery,db-arrow]"]# ---- Embedding / Models ----diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.pyindex 3a0bbef7..80b26836 100644--- a/semantica/ingest/__init__.py+++ b/semantica/ingest/__init__.py@@ -133,6 +133,11 @@ import importlibfrom typing import TYPE_CHECKING, Any, Dict, Tupleif TYPE_CHECKING:+ from .bigquery_ingestor import (+ BigQueryConnector,+ BigQueryData,+ BigQueryIngestor,+ )from .powerbi_ingestor import (PowerBIConnector,PowerBIData,@@ -260,6 +265,10 @@ _LAZY_EXPORTS: Dict[str, Tuple[str, str]] = {"PowerBIIngestor": (".powerbi_ingestor", "PowerBIIngestor"),"PowerBIData": (".powerbi_ingestor", "PowerBIData"),"PowerBIConnector": (".powerbi_ingestor", "PowerBIConnector"),+ # BigQuery ingestion+ "BigQueryIngestor": (".bigquery_ingestor", "BigQueryIngestor"),+ "BigQueryData": (".bigquery_ingestor", "BigQueryData"),+ "BigQueryConnector": (".bigquery_ingestor", "BigQueryConnector"),}_OPTIONAL_DEPENDENCY_MESSAGES = {@@ -306,6 +315,10 @@ _OPTIONAL_DEPENDENCY_MESSAGES = {"Redshift ingestion requires optional dependency 'redshift-connector'. ""Install it with: pip install 'semantica[db-redshift]'"),+ ".bigquery_ingestor": (+ "BigQuery ingestion requires optional dependency 'google-cloud-bigquery'. "+ "Install it with: pip install 'semantica[db-bigquery]'"+ ),}@@ -331,6 +344,7 @@ def __getattr__(name: str) -> Any:"simple_salesforce","lxml","redshift_connector",+ "google",))):@@ -382,6 +396,15 @@ def __getattr__(name: str) -> Any:if message:raise ImportError(message)+ if module_name == ".bigquery_ingestor" and name in {+ "BigQueryIngestor",+ "BigQueryConnector",+ }:+ if not getattr(module, "BIGQUERY_AVAILABLE", True):+ message = _OPTIONAL_DEPENDENCY_MESSAGES.get(module_name)+ if message:+ raise ImportError(message)+value = getattr(module, attr_name)globals()[name] = valuereturn value@@ -480,6 +503,10 @@ __all__ = ["PowerBIIngestor","PowerBIData","PowerBIConnector",+ # BigQuery ingestion+ "BigQueryIngestor",+ "BigQueryData",+ "BigQueryConnector",# Registry and Methods"MethodRegistry","method_registry",diff --git a/semantica/ingest/bigquery_ingestor.py b/semantica/ingest/bigquery_ingestor.pynew file mode 100644index 00000000..bb9a49b9--- /dev/null+++ b/semantica/ingest/bigquery_ingestor.py@@ -0,0 +1,1370 @@+"""BigQuery ingestion module.++Pulls data from Google BigQuery tables and queries and flattens it into+document dicts that the pipeline can feed to ``GraphBuilder``.++Design notes+------------+Three classes, matching the Snowflake/Databricks/Salesforce/Redshift ingestors:++- ``BigQueryData``: holds the rows returned by one table fetch or query+ (``data``, ``row_count``, ``columns``, ``table_name``, ``query``,+ ``project``, ``dataset``, ``location``, ``metadata``, ``ingested_at``).+ No SDK dependency — always importable.++- ``BigQueryConnector``: manages the ``google-cloud-bigquery`` client+ lifecycle. Raises ``ImportError`` at instantiation time when the+ optional ``google-cloud-bigquery`` package is absent. Supports+ Application Default Credentials (ADC) and service-account key-file+ authentication.++- ``BigQueryIngestor``: orchestrates ingestion. Composes+ ``BigQueryConnector`` and exposes ``ingest_table``, ``ingest_query``,+ ``get_table_schema``, ``list_tables``, ``export_as_documents``, and+ ``close``, together with context-manager support.++Authentication+--------------+**Application Default Credentials (ADC)** — the recommended mode for+managed environments (GKE, Cloud Run, Vertex AI) and local development+(``gcloud auth application-default login``)::++ conn = BigQueryConnector(project="my-project")++**Service account key file** — for CI/CD or environments without ambient+credentials. The path to a JSON key file exported from the GCP console::++ conn = BigQueryConnector(+ project="my-project",+ credentials_file="/run/secrets/sa-key.json",+ )++Set ``BIGQUERY_CREDENTIALS_FILE`` in the environment to avoid passing the+path in code.++SQL safety+----------+Table, dataset, and project names are validated before being interpolated+into query strings. BigQuery identifier validation permits the+characters ``[A-Za-z0-9_]``, with the project component additionally+allowing hyphens (``-``) because all valid GCP project IDs contain+hyphens. ``WHERE`` and ``ORDER BY`` fragments are checked with the+shared :func:`~semantica.ingest.db_ingestor._validate_sql_fragment`+helper which blocks statement separators, ``UNION``, DML/DDL keywords,+comment sequences, and time-based blind-injection oracles. Validated+identifier components are wrapped in backticks (BigQuery's quoting+character) before interpolation.++Optional dependency+-------------------+Install the SDK before using ``BigQueryConnector`` or+``BigQueryIngestor``::++ pip install "semantica[db-bigquery]"++or directly::++ pip install google-cloud-bigquery>=3.0.0++The top-level ``import semantica.ingest`` never imports+``google-cloud-bigquery`` eagerly; the SDK is loaded only when this+module is first accessed through the lazy-export mechanism in+``__init__.py``.+"""++from __future__ import annotations++import decimal+import os+import re+from dataclasses import dataclass, field+from datetime import date, datetime, time+from typing import Any, Dict, List, Optional, Tuple++from ..utils.exceptions import ProcessingError, ValidationError+from ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker+from .db_ingestor import _validate_sql_fragment++# ---------------------------------------------------------------------------+# Optional-dependency guard+# ---------------------------------------------------------------------------+# The module always imports cleanly. The sentinel fires at instantiation+# time (inside BigQueryConnector.__init__) so that:+# - ``from semantica.ingest import BigQueryData`` succeeds with no SDK+# - ``from semantica.ingest import BigQueryIngestor`` succeeds (lazy)+# - ``BigQueryConnector(...)`` raises a clear ImportError when SDK absent+# ---------------------------------------------------------------------------+try:+ from google.cloud import bigquery as _bigquery++ BIGQUERY_AVAILABLE = True+except (ImportError, OSError):+ _bigquery = None # type: ignore[assignment]+ BIGQUERY_AVAILABLE = False++__all__ = [+ "BigQueryData",+ "BigQueryConnector",+ "BigQueryIngestor",+]++_logger = get_logger("bigquery_ingestor")++# ---------------------------------------------------------------------------+# Identifier validation+# ---------------------------------------------------------------------------++# Standard BigQuery identifier: letter/underscore start, alphanumeric/underscore body.+_BQ_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")++# GCP project IDs allow hyphens (e.g. ``my-project-123``). The first+# character must be a letter; subsequent characters may be letters, digits,+# or hyphens. Unlike the general identifier regex, underscores are also+# accepted here because GCP silently maps them to hyphens in some contexts+# and existing customers rely on underscore-containing project IDs.+_BQ_PROJECT_ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")+++def _validate_bq_identifier(name: str, kind: str) -> str:+ """Validate a BigQuery table or dataset name for safe interpolation.++ Accepts names matching ``^[A-Za-z_][A-Za-z0-9_]*$``.++ Args:+ name: The identifier to validate.+ kind: Human-readable label used in error messages (e.g.+ ``"table_name"``).++ Returns:+ The unchanged name if valid.++ Raises:+ ValidationError: If the name does not match the expected pattern.+ """+ if not isinstance(name, str) or not _BQ_IDENTIFIER_RE.match(name):+ raise ValidationError(+ f"Invalid {kind}: {name!r}. Must start with a letter or "+ "underscore and contain only letters, digits, and underscores."+ )+ return name+++def _validate_bq_project_id(project_id: str) -> str:+ """Validate a GCP project ID for safe interpolation.++ Accepts identifiers matching ``^[A-Za-z][A-Za-z0-9_-]*$`` to cover+ real-world GCP project IDs that contain hyphens (e.g.+ ``my-project-123``). The generic SQL identifier validator+ (:func:`~semantica.ingest.db_ingestor._validate_sql_identifier`)+ rejects hyphens and therefore cannot be used here.++ Args:+ project_id: The GCP project ID to validate.++ Returns:+ The unchanged project ID if valid.++ Raises:+ ValidationError: If the project ID does not match the expected+ pattern.+ """+ if not isinstance(project_id, str) or not _BQ_PROJECT_ID_RE.match(project_id):+ raise ValidationError(+ f"Invalid BigQuery project ID: {project_id!r}. "+ "Must start with a letter and contain only letters, digits, "+ "hyphens, and underscores."+ )+ return project_id+++def _bq_quote(identifier: str) -> str:+ """Wrap a validated identifier in BigQuery backtick quoting.++ BigQuery uses backticks (`` ` ``) to quote identifiers containing+ special characters. Internal backticks are doubled.++ Args:+ identifier: Already-validated identifier string.++ Returns:+ Backtick-quoted identifier.+ """+ return "`" + identifier.replace("`", "``") + "`"+++def _build_table_ref(+ table_name: str,+ dataset: Optional[str],+ project: Optional[str],+) -> str:+ """Build a fully-qualified, backtick-quoted BigQuery table reference.++ Components that are ``None`` or empty are omitted.++ Args:+ table_name: Already-validated table name.+ dataset: Optional dataset name (already validated).+ project: Optional project ID (already validated).++ Returns:+ A BigQuery table reference such as+ `` `my-project`.`my_dataset`.`my_table` `` or just+ `` `my_table` ``.+ """+ parts = []+ if project:+ parts.append(_bq_quote(project))+ if dataset:+ parts.append(_bq_quote(dataset))+ parts.append(_bq_quote(table_name))+ return ".".join(parts)+++# ---------------------------------------------------------------------------+# BigQueryData+# ---------------------------------------------------------------------------+++@dataclass+class BigQueryData:+ """Records returned from a BigQuery table or query.++ Attributes:+ data: List of row dictionaries. Values are JSON-serialisable+ Python types (see :meth:`BigQueryIngestor._convert_rows`).+ row_count: Number of rows in ``data``.+ columns: Ordered list of column names present in ``data``.+ table_name: Source table name, or ``None`` for raw-query results.+ query: SQL query string used to produce these rows, or ``None``.+ project: GCP project ID used for the ingestion, or ``None``.+ dataset: BigQuery dataset name used for the ingestion, or+ ``None``.+ location: BigQuery location (e.g. ``"US"`` or+ ``"europe-west1"``), or ``None`` (defaults to the project+ default).+ metadata: Arbitrary extra metadata.+ ingested_at: Timestamp recorded when this object was created.+ """++ data: List[Dict[str, Any]]+ row_count: int+ columns: List[str]+ table_name: Optional[str] = None+ query: Optional[str] = None+ project: Optional[str] = None+ dataset: Optional[str] = None+ location: Optional[str] = None+ metadata: Dict[str, Any] = field(default_factory=dict)+ ingested_at: datetime = field(default_factory=datetime.now)+++# ---------------------------------------------------------------------------+# BigQueryConnector+# ---------------------------------------------------------------------------+++class BigQueryConnector:+ """Manages the ``google-cloud-bigquery`` client lifecycle.++ Responsibilities:++ * Reads credentials from constructor arguments, falling back to+ environment variables with ``BIGQUERY_*`` names.+ * Validates that the project is configured *before* any network call+ is made (project is the minimum required identifier for BigQuery).+ * Exposes :meth:`connect`, :meth:`disconnect`, and+ :meth:`test_connection` so the ingestor (and tests) can control the+ client lifecycle explicitly.+ * **Connection reuse**: :meth:`connect` returns the existing client+ when one is already open, preventing duplicate auth round-trips and+ resource leaks when used as a context manager.++ Supported Authentication Modes+ --------------------------------+ **Application Default Credentials (ADC)** — recommended for GKE,+ Cloud Run, Vertex AI, and local development. No explicit credential+ argument is needed; the SDK resolves credentials automatically from+ the environment::++ import os+ from semantica.ingest import BigQueryConnector++ connector = BigQueryConnector(+ project=os.getenv("BIGQUERY_PROJECT"),+ )++ To configure ADC locally::++ gcloud auth application-default login++ In production, attach a service account to the workload identity and+ no credential file is required.++ **Service Account Key File** — for CI/CD or environments without+ ambient credentials::++ import os+ from semantica.ingest import BigQueryConnector++ connector = BigQueryConnector(+ project=os.getenv("BIGQUERY_PROJECT"),+ credentials_file=os.getenv("BIGQUERY_CREDENTIALS_FILE"),+ )++ The credentials file is a JSON key file downloaded from the GCP+ console (*IAM & Admin → Service Accounts → Keys*).++ Environment Variables+ ----------------------+ Every constructor parameter has an environment-variable fallback:++ * ``BIGQUERY_PROJECT``+ * ``BIGQUERY_DATASET``+ * ``BIGQUERY_LOCATION``+ * ``BIGQUERY_CREDENTIALS_FILE`` (path to service-account JSON key)++ Raises:+ ImportError: When ``google-cloud-bigquery`` is not installed.+ ValidationError: When required configuration is incomplete.+ """++ def __init__(+ self,+ project: Optional[str] = None,+ dataset: Optional[str] = None,+ location: Optional[str] = None,+ credentials_file: Optional[str] = None,+ **config: Any,+ ) -> None:+ """Initialise the connector and validate configuration.++ Args:+ project: GCP project ID. Resolved from ``BIGQUERY_PROJECT``+ environment variable when not supplied.+ dataset: Default BigQuery dataset. Resolved from+ ``BIGQUERY_DATASET`` environment variable.+ location: BigQuery job location, e.g. ``"US"`` or+ ``"europe-west1"``. Resolved from ``BIGQUERY_LOCATION``+ environment variable.+ credentials_file: Path to a service-account JSON key file.+ When ``None`` (default), Application Default Credentials+ are used. Resolved from ``BIGQUERY_CREDENTIALS_FILE``+ environment variable.+ **config: Extra keyword arguments forwarded to+ ``bigquery.Client()``.++ Raises:+ ImportError: When ``google-cloud-bigquery`` is not installed.+ ValidationError: When ``project`` cannot be resolved.+ """+ if not BIGQUERY_AVAILABLE:+ raise ImportError(+ "google-cloud-bigquery is required for BigQueryConnector. "+ 'Install it with: pip install "semantica[db-bigquery]"'+ )++ self.logger = _logger++ # ------------------------------------------------------------------+ # Resolve configuration — explicit args override env vars.+ # ``credentials_file`` is a path (not a secret value), but we store+ # it under a private attribute as a convention (it points to key+ # material) and never include it in log messages.+ # ------------------------------------------------------------------+ self.project: Optional[str] = project or os.getenv("BIGQUERY_PROJECT")+ self.dataset: Optional[str] = dataset or os.getenv("BIGQUERY_DATASET")+ self.location: Optional[str] = location or os.getenv("BIGQUERY_LOCATION")+ self._credentials_file: Optional[str] = credentials_file or os.getenv(+ "BIGQUERY_CREDENTIALS_FILE"+ )+ self._extra_config: Dict[str, Any] = config++ # Internal client — None until connect() is called.+ self._client: Optional[Any] = None++ # Validate that project is resolvable before any network call.+ self._validate_config()++ self.logger.debug(+ "BigQuery connector initialised (project=%s, dataset=%s, location=%s, "+ "credentials_file=%s)",+ self.project,+ self.dataset,+ self.location,+ "set" if self._credentials_file else "unset (ADC)",+ )++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ def _validate_config(self) -> None:+ """Raise :class:`~semantica.utils.exceptions.ValidationError` when+ required configuration is absent.++ BigQuery's SDK can resolve the project from the ambient environment+ (``GOOGLE_CLOUD_PROJECT``, ADC metadata, etc.), but relying on that+ silently makes the connector's behaviour environment-dependent.+ We require an explicit project so failures are immediate and+ obvious.++ Raises:+ ValidationError: When ``project`` is not set.+ """+ if not self.project:+ raise ValidationError(+ "BigQuery project is required. "+ "Provide via 'project' or the BIGQUERY_PROJECT environment variable."+ )++ def _build_client(self) -> Any:+ """Create and return a ``bigquery.Client`` instance.++ Selects the credential strategy based on available configuration:+ * ``_credentials_file`` is set → load a+ ``google.oauth2.service_account.Credentials`` from the file.+ * Otherwise → pass no ``credentials`` argument and let the SDK+ resolve Application Default Credentials.++ Returns:+ A ``google.cloud.bigquery.Client`` instance.++ Raises:+ ProcessingError: If the client cannot be created.+ """+ kwargs: Dict[str, Any] = {"project": self.project}++ if self.location:+ kwargs["location"] = self.location++ if self._credentials_file:+ try:+ from google.oauth2 import service_account as _sa++ credentials = _sa.Credentials.from_service_account_file(+ self._credentials_file,+ scopes=["https://www.googleapis.com/auth/bigquery"],+ )+ kwargs["credentials"] = credentials+ except Exception as exc:+ raise ProcessingError(+ f"Failed to load BigQuery credentials from file: "+ f"{type(exc).__name__}"+ ) from exc++ kwargs.update(self._extra_config)++ try:+ return _bigquery.Client(**kwargs)+ except Exception as exc:+ raise ProcessingError(+ f"Failed to create BigQuery client: {type(exc).__name__}"+ ) from exc++ # ------------------------------------------------------------------+ # Public properties+ # ------------------------------------------------------------------++ @property+ def client(self) -> Optional[Any]:+ """The active ``google.cloud.bigquery.Client`` instance, or ``None``."""+ return self._client++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------++ def connect(self) -> Any:+ """Create and return the BigQuery client.++ If a client is already open, returns it immediately without+ re-authenticating (connection-reuse semantics matching the+ Salesforce, Databricks, and Redshift connectors).++ Returns:+ The ``google.cloud.bigquery.Client`` instance.++ Raises:+ ProcessingError: If the client cannot be created.+ """+ if self._client is not None:+ return self._client++ try:+ self._client = self._build_client()+ self.logger.info(+ "Connected to BigQuery (project=%s, location=%s)",+ self.project,+ self.location,+ )+ return self._client+ except ProcessingError:+ self._client = None+ raise+ except Exception as exc:+ self._client = None+ self.logger.error(+ "Failed to connect to BigQuery: %s", type(exc).__name__+ )+ raise ProcessingError(+ f"Failed to connect to BigQuery: {type(exc).__name__}"+ ) from exc++ def disconnect(self) -> None:+ """Close the BigQuery client and release the reference.++ Safe to call when already disconnected — subsequent calls are+ no-ops.+ """+ if self._client is not None:+ try:+ self._client.close()+ except Exception: # noqa: BLE001+ pass+ finally:+ self._client = None+ self.logger.info("Disconnected from BigQuery.")++ def test_connection(self) -> bool:+ """Verify connectivity by issuing a cheap query.++ Opens a client (or reuses an existing one), runs+ ``SELECT 1`` to confirm the session is live, then closes+ the client if it was opened by this call.++ Returns:+ ``True`` if the ping succeeds, ``False`` for any failure.+ """+ already_connected = self._client is not None+ try:+ client = self.connect()+ query_job = client.query("SELECT 1")+ # Consume the result to confirm the job completed successfully.+ list(query_job.result())+ return True+ except Exception as exc:+ self.logger.debug(+ "BigQuery connection test failed: %s", type(exc).__name__+ )+ return False+ finally:+ if not already_connected:+ self.disconnect()+++# ---------------------------------------------------------------------------+# BigQueryIngestor+# ---------------------------------------------------------------------------+++class BigQueryIngestor:+ """Google BigQuery data ingestor for the Semantica framework.++ Wraps :class:`BigQueryConnector` and exposes table and query+ ingestion, schema introspection, and document export.++ Args:+ project: GCP project ID. Resolved from ``BIGQUERY_PROJECT``+ environment variable when not supplied.+ dataset: Default BigQuery dataset. Resolved from+ ``BIGQUERY_DATASET`` environment variable.+ location: BigQuery job location, e.g. ``"US"`` or+ ``"europe-west1"``. Resolved from ``BIGQUERY_LOCATION``+ environment variable.+ credentials_file: Path to a service-account JSON key file.+ When ``None``, Application Default Credentials are used.+ Resolved from ``BIGQUERY_CREDENTIALS_FILE`` environment+ variable.+ connector: An existing :class:`BigQueryConnector` to reuse.+ Useful when you want to share one client across multiple+ ingestor instances.+ config: Optional extra configuration dict forwarded to the+ connector.+ **kwargs: Additional keyword arguments merged into ``config``.++ Raises:+ ImportError: When ``google-cloud-bigquery`` is not installed.+ ValidationError: When required configuration is incomplete.++ Example::++ import os+ from semantica.ingest import BigQueryIngestor++ # ADC authentication+ ingestor = BigQueryIngestor(+ project=os.getenv("BIGQUERY_PROJECT"),+ dataset=os.getenv("BIGQUERY_DATASET"),+ )++ # Context manager — preferred for production use+ with BigQueryIngestor(+ project=os.getenv("BIGQUERY_PROJECT"),+ dataset=os.getenv("BIGQUERY_DATASET"),+ ) as bq:+ data = bq.ingest_table("orders", limit=1000)+ documents = bq.export_as_documents(data)+ """++ def __init__(+ self,+ project: Optional[str] = None,+ dataset: Optional[str] = None,+ location: Optional[str] = None,+ credentials_file: Optional[str] = None,+ connector: Optional[BigQueryConnector] = None,+ config: Optional[Dict[str, Any]] = None,+ **kwargs: Any,+ ) -> None:+ self.logger = _logger++ self.config: Dict[str, Any] = config or {}+ self.config.update(kwargs)++ # Instantiate a connector unless one is supplied.+ # ImportError propagates when SDK is absent; ValidationError when+ # configuration is incomplete.+ self.connector: BigQueryConnector = connector or BigQueryConnector(+ project=project,+ dataset=dataset,+ location=location,+ credentials_file=credentials_file,+ **self.config,+ )++ # Progress tracker — consistent with all other ingestors.+ self.progress_tracker = get_progress_tracker()+ if not self.progress_tracker.enabled:+ self.progress_tracker.enabled = True++ self.logger.debug("BigQuery ingestor initialised.")++ # ------------------------------------------------------------------+ # Context-manager support+ # ------------------------------------------------------------------++ def __enter__(self) -> "BigQueryIngestor":+ """Open the BigQuery client on context entry."""+ self.connector.connect()+ return self++ def __exit__(+ self,+ exc_type: Any,+ exc_val: Any,+ exc_tb: Any,+ ) -> None:+ """Close the BigQuery client on context exit."""+ self.close()++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------++ def close(self) -> None:+ """Disconnect from BigQuery and release the client."""+ self.connector.disconnect()++ # ------------------------------------------------------------------+ # Ingestion — ingest_table+ # ------------------------------------------------------------------++ def ingest_table(+ self,+ table_name: str,+ dataset: Optional[str] = None,+ project: Optional[str] = None,+ limit: Optional[int] = None,+ where: Optional[str] = None,+ order_by: Optional[str] = None,+ **options: Any,+ ) -> BigQueryData:+ """Fetch rows from a BigQuery table.++ Builds a ``SELECT * FROM <table>`` query with optional+ ``WHERE``, ``ORDER BY``, and ``LIMIT`` clauses and executes it+ against BigQuery.++ All identifier components (``table_name``, ``dataset``,+ ``project``) are validated before interpolation:+ table and dataset names must match+ ``^[A-Za-z_][A-Za-z0-9_]*$``; the project ID must match+ ``^[A-Za-z][A-Za-z0-9_-]*$`` (hyphens permitted).+ Validated components are wrapped in backticks. ``WHERE`` and+ ``ORDER BY`` fragments are validated with+ :func:`~semantica.ingest.db_ingestor._validate_sql_fragment`.+ All validation happens before any network call.++ Connection lifecycle: if the ingestor is used as a context+ manager the existing client is reused; standalone calls open a+ transient client and close it in a ``finally`` block.++ Args:+ table_name: Name of the BigQuery table to query.+ dataset: Override dataset name (defaults to the connector's+ configured dataset).+ project: Override project ID (defaults to the connector's+ configured project).+ limit: Maximum number of rows to return.+ where: SQL ``WHERE`` clause fragment (without the+ ``WHERE`` keyword). Trusted / operator input only —+ do not pass raw end-user text.+ order_by: SQL ``ORDER BY`` clause fragment (without the+ keyword). Same trust requirement.+ **options: Reserved for future use.++ Returns:+ :class:`BigQueryData` with ``data``, ``row_count``,+ ``columns``, ``table_name``, ``project``, ``dataset``,+ ``location``, ``query``, and ``metadata`` populated.++ Raises:+ ValidationError: If any identifier or SQL fragment fails+ safety validation.+ ProcessingError: If the query fails or the client cannot+ be created.+ """+ effective_project = project or self.connector.project+ effective_dataset = dataset or self.connector.dataset++ # ------------------------------------------------------------------+ # Validate all identifiers and SQL fragments BEFORE connecting so+ # invalid inputs are rejected cheaply without any network call.+ # ------------------------------------------------------------------+ if not effective_dataset:+ raise ValidationError(+ "BigQuery dataset is required for ingest_table(). "+ "Provide via 'dataset' argument or the BIGQUERY_DATASET "+ "environment variable."+ )+ _validate_bq_identifier(table_name, "table_name")+ _validate_bq_identifier(effective_dataset, "dataset")+ if effective_project:+ _validate_bq_project_id(effective_project)+ if where:+ _validate_sql_fragment(where, "where")+ if order_by:+ _validate_sql_fragment(order_by, "order_by")++ table_ref = _build_table_ref(table_name, effective_dataset, effective_project)++ tracking_id = self.progress_tracker.start_tracking(+ file=table_ref,+ module="ingest",+ submodule="BigQueryIngestor",+ message=f"Table: {table_ref}",+ )++ try:+ already_connected = self.connector.client is not None+ client = self.connector.connect()++ try:+ query = f"SELECT * FROM {table_ref}"++ if where:+ query += f" WHERE {where}"+ if order_by:+ query += f" ORDER BY {order_by}"+ if limit is not None:+ query += f" LIMIT {int(limit)}"++ self.logger.debug("Executing ingest_table query: %s", query)++ self.progress_tracker.update_tracking(+ tracking_id, message="Executing query..."+ )++ query_job = client.query(query)++ self.progress_tracker.update_tracking(+ tracking_id, message="Fetching results..."+ )++ result_iter = query_job.result()+ # Extract column names from the RowIterator schema BEFORE+ # materialising rows so zero-row results preserve the+ # declared schema (Finding 2).+ schema_columns = (+ [field.name for field in result_iter.schema]+ if result_iter.schema+ else None+ )+ rows = list(result_iter)+ columns, data = self._rows_to_dicts(rows, schema_columns=schema_columns)+ data = self._convert_rows(data)++ finally:+ if not already_connected:+ self.connector.disconnect()++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Ingested {len(data)} rows",+ )+ self.logger.info(+ "ingest_table completed: %s — %d row(s)", table_ref, len(data)+ )++ return BigQueryData(+ data=data,+ row_count=len(data),+ columns=columns,+ table_name=table_name,+ project=effective_project,+ dataset=effective_dataset,+ location=self.connector.location,+ query=query,+ metadata={"query": query},+ )++ except (ValidationError, ProcessingError):+ self.progress_tracker.stop_tracking(+ tracking_id, status="failed", message="Query failed"+ )+ raise+ except Exception as exc:+ self.progress_tracker.stop_tracking(+ tracking_id, status="failed", message=str(exc)+ )+ self.logger.error(+ "Failed to ingest table %s: %s", table_name, type(exc).__name__+ )+ raise ProcessingError(+ f"Failed to ingest BigQuery table '{table_name}': "+ f"{type(exc).__name__}"+ ) from exc++ # ------------------------------------------------------------------+ # Ingestion — ingest_query+ # ------------------------------------------------------------------++ def ingest_query(+ self,+ query: str,+ job_config: Optional[Any] = None,+ **options: Any,+ ) -> BigQueryData:+ """Execute a raw SQL query and return all matching rows.++ Passes the query verbatim to the BigQuery client. The caller+ is responsible for the correctness and safety of the query+ string.++ For parameterised queries pass a+ ``google.cloud.bigquery.QueryJobConfig`` with ``query_parameters``+ set via the ``job_config`` argument.++ Connection lifecycle mirrors :meth:`ingest_table`: standalone+ calls open and close a transient client; calls made inside a+ context manager reuse the open client.++ Args:+ query: Complete Standard SQL query string.+ job_config: Optional ``bigquery.QueryJobConfig`` instance for+ parameterised queries, timeouts, dry-run mode, etc.+ **options: Reserved for future use.++ Returns:+ :class:`BigQueryData` with ``data``, ``row_count``,+ ``columns``, and ``query`` populated.++ Raises:+ ProcessingError: If the query fails or the client cannot be+ created.+ """+ tracking_id = self.progress_tracker.start_tracking(+ file="query",+ module="ingest",+ submodule="BigQueryIngestor",+ message="Executing query...",+ )++ try:+ already_connected = self.connector.client is not None+ client = self.connector.connect()++ try:+ self.logger.debug("Executing ingest_query: %s", query[:200])++ self.progress_tracker.update_tracking(+ tracking_id, message="Executing query..."+ )++ if job_config is not None:+ query_job = client.query(query, job_config=job_config)+ else:+ query_job = client.query(query)++ self.progress_tracker.update_tracking(+ tracking_id, message="Fetching results..."+ )++ result_iter = query_job.result()+ # Extract column names from the RowIterator schema BEFORE+ # materialising rows so zero-row results preserve the+ # declared schema (Finding 2).+ schema_columns = (+ [field.name for field in result_iter.schema]+ if result_iter.schema+ else None+ )+ rows = list(result_iter)+ columns, data = self._rows_to_dicts(rows, schema_columns=schema_columns)+ data = self._convert_rows(data)++ finally:+ if not already_connected:+ self.connector.disconnect()++ self.progress_tracker.stop_tracking(+ tracking_id,+ status="completed",+ message=f"Query completed: {len(data)} rows",+ )+ self.logger.info("ingest_query completed: %d row(s)", len(data))++ return BigQueryData(+ data=data,+ row_count=len(data),+ columns=columns,+ query=query,+ project=self.connector.project,+ dataset=self.connector.dataset,+ location=self.connector.location,+ metadata={},+ )++ except (ValidationError, ProcessingError):+ self.progress_tracker.stop_tracking(+ tracking_id, status="failed", message="Query failed"+ )+ raise+ except Exception as exc:+ self.progress_tracker.stop_tracking(+ tracking_id, status="failed", message=str(exc)+ )+ self.logger.error(+ "Failed to execute query: %s", type(exc).__name__+ )+ raise ProcessingError(+ f"Failed to execute BigQuery query: {type(exc).__name__}"+ ) from exc++ # ------------------------------------------------------------------+ # Schema discovery — get_table_schema+ # ------------------------------------------------------------------++ def get_table_schema(+ self,+ table_name: str,+ dataset: Optional[str] = None,+ project: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Return schema metadata for a BigQuery table.++ Uses the ``bigquery.Client.get_table()`` API to retrieve the+ table's ``SchemaField`` list without executing a query. The+ result includes column names, types, nullability, and the+ table-level row count.++ Args:+ table_name: Name of the BigQuery table to introspect.+ dataset: Override dataset name. Defaults to the connector's+ configured dataset.+ project: Override project ID. Defaults to the connector's+ configured project.++ Returns:+ A dictionary with three keys:++ ``"columns"``+ Ordered list of column dicts, each containing+ ``"name"``, ``"type"``, and ``"nullable"`` (``bool``).++ ``"num_rows"``+ Approximate row count reported by BigQuery, or ``None``+ when unavailable.++ ``"clustering_fields"``+ List of clustering-column names, or an empty list when+ the table is not clustered.++ Raises:+ ValidationError: If *table_name*, *dataset*, or *project*+ fails identifier validation.+ ProcessingError: If the metadata call fails.+ """+ effective_project = project or self.connector.project+ effective_dataset = dataset or self.connector.dataset++ if not effective_dataset:+ raise ValidationError(+ "BigQuery dataset is required for get_table_schema(). "+ "Provide via 'dataset' argument or the BIGQUERY_DATASET "+ "environment variable."+ )+ _validate_bq_identifier(table_name, "table_name")+ _validate_bq_identifier(effective_dataset, "dataset")+ if effective_project:+ _validate_bq_project_id(effective_project)++ # Build the table reference string expected by get_table().+ # If project and dataset are available, use the fully-qualified form.+ parts = []+ if effective_project:+ parts.append(effective_project)+ if effective_dataset:+ parts.append(effective_dataset)+ parts.append(table_name)+ table_ref_str = ".".join(parts)++ try:+ already_connected = self.connector.client is not None+ client = self.connector.connect()++ try:+ table = client.get_table(table_ref_str)+ finally:+ if not already_connected:+ self.connector.disconnect()++ columns = [+ {+ "name": f.name,+ "type": f.field_type,+ "nullable": f.mode != "REQUIRED",+ }+ for f in (table.schema or [])+ ]++ self.logger.debug(+ "get_table_schema: %s — %d column(s)",+ table_ref_str,+ len(columns),+ )++ return {+ "columns": columns,+ "num_rows": getattr(table, "num_rows", None),+ "clustering_fields": list(table.clustering_fields or []),+ }++ except (ValidationError, ProcessingError):+ raise+ except Exception as exc:+ self.logger.error(+ "Failed to get schema for %s: %s", table_name, type(exc).__name__+ )+ raise ProcessingError(+ f"Failed to get schema for BigQuery table '{table_name}': "+ f"{type(exc).__name__}"+ ) from exc++ # ------------------------------------------------------------------+ # Schema discovery — list_tables+ # ------------------------------------------------------------------++ def list_tables(+ self,+ dataset: Optional[str] = None,+ project: Optional[str] = None,+ ) -> List[str]:+ """Return the names of all tables in the specified dataset.++ Uses ``bigquery.Client.list_tables()`` to enumerate table IDs.+ The result includes regular tables, views, and materialized views+ (matching BigQuery's API behaviour).++ Args:+ dataset: Override dataset name. Defaults to the connector's+ configured dataset.+ project: Override project ID. Defaults to the connector's+ configured project.++ Returns:+ Sorted list of table-name strings, or an empty list when the+ dataset contains no tables.++ Raises:+ ValidationError: If *dataset* or *project* fails identifier+ validation, or if no dataset is configured.+ ProcessingError: If the list call fails.+ """+ effective_project = project or self.connector.project+ effective_dataset = dataset or self.connector.dataset++ if not effective_dataset:+ raise ValidationError(+ "BigQuery dataset is required for list_tables(). "+ "Provide via 'dataset' argument or the BIGQUERY_DATASET "+ "environment variable."+ )++ _validate_bq_identifier(effective_dataset, "dataset")+ if effective_project:+ _validate_bq_project_id(effective_project)++ # Build dataset reference string expected by list_tables().+ dataset_ref_str = (+ f"{effective_project}.{effective_dataset}"+ if effective_project+ else effective_dataset+ )++ try:+ already_connected = self.connector.client is not None+ client = self.connector.connect()++ try:+ tables = list(client.list_tables(dataset_ref_str))+ finally:+ if not already_connected:+ self.connector.disconnect()++ table_names = sorted(t.table_id for t in tables)+ self.logger.debug(+ "list_tables: %d table(s) in dataset '%s'",+ len(table_names),+ effective_dataset,+ )+ return table_names++ except (ValidationError, ProcessingError):+ raise+ except Exception as exc:+ self.logger.error(+ "Failed to list tables in dataset '%s': %s",+ effective_dataset,+ type(exc).__name__,+ )+ raise ProcessingError(+ f"Failed to list BigQuery tables in dataset '{effective_dataset}': "+ f"{type(exc).__name__}"+ ) from exc++ # ------------------------------------------------------------------+ # Document export+ # ------------------------------------------------------------------++ def export_as_documents(+ self,+ data: BigQueryData,+ id_field: str = "id",+ text_fields: Optional[List[str]] = None,+ ) -> List[Dict[str, Any]]:+ """Convert :class:`BigQueryData` to the Semantica document format.++ Produces the same ``{"id", "text", "metadata"}`` shape used by+ :class:`~semantica.ingest.snowflake_ingestor.SnowflakeIngestor`,+ :class:`~semantica.ingest.databricks_ingestor.DatabricksIngestor`,+ and :class:`~semantica.ingest.redshift_ingestor.RedshiftIngestor`,+ making :class:`BigQueryData` directly usable with+ :class:`~semantica.kg.graph_builder.GraphBuilder`.++ **ID resolution**+ ``str(row.get(id_field, idx))`` — the row-index integer is+ used as a deterministic fallback when *id_field* is absent,+ cast to a string. This matches the Snowflake/Redshift+ convention.++ **Text composition**+ * When *text_fields* is provided: only those fields are used;+ each non-``None`` value is converted to a string and joined+ with a single space.+ * When *text_fields* is ``None``: only ``str``-typed values+ are joined (integers, floats, booleans, ``None``, and+ ``Decimal`` are excluded). This matches the+ Snowflake/Databricks default behaviour.++ **Metadata**+ ``{"source": "bigquery", "table": ..., "project": ...,+ "dataset": ..., "location": ..., "row_data": <full row>}``++ Args:+ data: A :class:`BigQueryData` object returned by+ :meth:`ingest_table` or :meth:`ingest_query`.+ id_field: Row field to use as the document ``"id"``.+ Defaults to ``"id"``.+ text_fields: List of field names whose values form the+ document ``"text"``. When ``None``, all string-typed+ field values are joined.++ Returns:+ List of document dictionaries::++ [+ {+ "id": str,+ "text": str,+ "metadata": {+ "source": "bigquery",+ "table": str | None,+ "project": str | None,+ "dataset": str | None,+ "location": str | None,+ "row_data": dict,+ },+ },+ ...+ ]+ """+ documents: List[Dict[str, Any]] = []++ for idx, row in enumerate(data.data):+ # Treat a present-but-None id_field value the same as a+ # missing key: fall back to the row index. This prevents+ # every null-id row from receiving the shared string "None"+ # as its document identifier (Finding 3).+ raw_id = row.get(id_field)+ doc_id = str(raw_id) if raw_id is not None else str(idx)++ doc: Dict[str, Any] = {+ "id": doc_id,+ "metadata": {+ "source": "bigquery",+ "table": data.table_name,+ "project": data.project,+ "dataset": data.dataset,+ "location": data.location,+ },+ }++ if text_fields:+ text_parts = [+ str(row[f])+ for f in text_fields+ if f in row and row[f] is not None+ ]+ else:+ text_parts = [+ value+ for value in row.values()+ if isinstance(value, str)+ ]++ doc["text"] = " ".join(text_parts)+ doc["metadata"]["row_data"] = row++ documents.append(doc)++ self.logger.debug(+ "export_as_documents: exported %d document(s)", len(documents)+ )+ return documents++ # ------------------------------------------------------------------+ # Internal helpers+ # ------------------------------------------------------------------++ @staticmethod+ def _rows_to_dicts(+ rows: List[Any],+ schema_columns: Optional[List[str]] = None,+ ) -> Tuple[List[str], List[Dict[str, Any]]]:+ """Convert BigQuery ``Row`` objects to plain dictionaries.++ ``google.cloud.bigquery.Row`` supports ``dict(row)`` and+ ``row.keys()``. Column names are derived from *schema_columns*+ when supplied (populated from the ``RowIterator.schema`` before+ row materialisation, so empty result sets preserve the declared+ schema). When *schema_columns* is ``None`` and rows are present,+ column names are taken from the first row. When both are absent+ the column list is empty.++ Args:+ rows: List of ``google.cloud.bigquery.Row`` objects from a+ completed ``QueryJob``.+ schema_columns: Optional ordered list of column names derived+ from the ``RowIterator`` schema before rows are fetched.+ Pass this to preserve columns for zero-row results.++ Returns:+ A ``(columns, data)`` tuple where *columns* is the ordered+ list of column-name strings and *data* is the list of row+ dictionaries.+ """+ if schema_columns is not None:+ columns = schema_columns+ elif rows:+ columns = list(rows[0].keys())+ else:+ columns = []+ data = [dict(row) for row in rows]+ return columns, data++ @staticmethod+ def _convert_value(value: Any) -> Any:+ """Recursively convert a single value to a JSON-serialisable type.++ Handles scalars, ``dict``-like BigQuery RECORD/STRUCT values, and+ ``list``-like REPEATED field values at every nesting level so that+ nested records containing dates, decimals, or bytes do not reach+ ``BigQueryData.data`` or document metadata in their raw SDK form.++ Conversion rules (applied at every nesting level):++ * ``datetime`` → ISO-8601 string (checked before ``date`` because+ ``datetime`` is a subclass of ``date``).+ * ``date`` / ``time`` → ISO-8601 string.+ * ``decimal.Decimal`` → ``str`` (preserves full NUMERIC precision).+ * ``bytes`` → UTF-8 decoded string; falls back to ``str()`` on+ ``UnicodeDecodeError``.+ * ``dict`` / mapping → recursively converted ``dict``.+ * ``list`` / sequence (but not ``str`` / ``bytes``) → recursively+ converted ``list``.+ * Everything else (``int``, ``float``, ``bool``, ``None``,+ ``str``) → passed through unchanged.++ Args:+ value: Any value returned by the BigQuery Python client.++ Returns:+ A JSON-serialisable Python value.+ """+ if isinstance(value, datetime):+ return value.isoformat()+ if isinstance(value, date):+ # Checked AFTER datetime: datetime is a subclass of date.+ return value.isoformat()+ if isinstance(value, time):+ return value.isoformat()+ if isinstance(value, decimal.Decimal):+ return str(value)+ if isinstance(value, bytes):+ try:+ return value.decode("utf-8")+ except UnicodeDecodeError:+ return str(value)+ if isinstance(value, dict):+ return {k: BigQueryIngestor._convert_value(v) for k, v in value.items()}+ # Handle list-like repeated fields; exclude str/bytes which are+ # also sequences but must not be iterated character-by-character.+ if isinstance(value, (list, tuple)):+ return [BigQueryIngestor._convert_value(item) for item in value]+ return value++ def _convert_rows(+ self, rows: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """Convert row dicts to JSON-serialisable format at every level.++ Delegates each top-level value to :meth:`_convert_value`, which+ recurses into BigQuery RECORD (STRUCT) and REPEATED fields so that+ nested dates, decimals, bytes, or further sub-records are converted+ correctly rather than left as raw SDK objects.++ Args:+ rows: List of row dictionaries produced by+ :meth:`_rows_to_dicts`.++ Returns:+ New list of row dictionaries with type conversions applied+ at all nesting levels.+ """+ return [+ {key: self._convert_value(value) for key, value in row.items()}+ for row in rows+ ]diff --git a/tests/test_bigquery_ingestor.py b/tests/test_bigquery_ingestor.pynew file mode 100644index 00000000..9d389a80--- /dev/null+++ b/tests/test_bigquery_ingestor.py@@ -0,0 +1,2108 @@+"""+Unit tests for BigQueryConnector and BigQueryIngestor.++All google-cloud-bigquery API calls are mocked — no real GCP project or+BigQuery dataset is required.++Test structure mirrors tests/test_redshift_ingestor.py and+tests/test_salesforce_ingestor.py:+ - autouse fixture injects a minimal google-cloud-bigquery stub when the+ SDK is not installed, so the test suite runs in both environments.+ - Each test that needs the connector to appear available patches+ ``BIGQUERY_AVAILABLE`` to ``True`` and ``_bigquery`` to a+ ``MagicMock``.+ - Credentials are always supplied so secret values are never embedded+ in assertions.+"""++from __future__ import annotations++import decimal+import os+from datetime import date, datetime, time+from unittest.mock import MagicMock, Mock, call, patch++import pytest++# ---------------------------------------------------------------------------+# Optional SDK detection+# ---------------------------------------------------------------------------+try:+ from google.cloud import bigquery as _bq_sdk # noqa: F401++ BIGQUERY_SDK_AVAILABLE = True+except ImportError:+ BIGQUERY_SDK_AVAILABLE = False+++# ---------------------------------------------------------------------------+# autouse fixture — inject stub when SDK is absent+# ---------------------------------------------------------------------------++[email protected](autouse=True)+def _mock_bigquery_sdk_if_needed():+ """Inject a minimal google-cloud-bigquery stub when the SDK is not installed.++ Design constraints (mirroring test_salesforce_ingestor.py):+ 1. Tests in ``TestImportBehaviourWithoutLib`` deliberately exercise the+ production missing-dependency guard (``BIGQUERY_AVAILABLE=False``).+ They must *not* receive the stub.+ 2. Every other test needs the stub so imports work even without the SDK.+ 3. After each stubbed test, any BigQuery symbols cached in the package+ globals are removed so subsequent availability checks re-run the guard.+ """+ import sys++ # Only inject the stub when the real SDK is absent.+ if not BIGQUERY_SDK_AVAILABLE:+ # Build a minimal stub hierarchy that satisfies all import paths+ # used by bigquery_ingestor.py.+ bq_stub = MagicMock()+ google_stub = MagicMock()+ google_cloud_stub = MagicMock()+ google_auth_stub = MagicMock()+ google_api_core_stub = MagicMock()+ google_oauth2_stub = MagicMock()+ google_oauth2_sa_stub = MagicMock()++ class _GAPIError(Exception):+ pass++ class _CredentialsError(Exception):+ pass++ bq_stub.Client = MagicMock()+ google_api_core_stub.exceptions = MagicMock()+ google_api_core_stub.exceptions.GoogleAPICallError = _GAPIError+ google_auth_stub.exceptions = MagicMock()+ google_auth_stub.exceptions.DefaultCredentialsError = _CredentialsError+ google_oauth2_sa_stub.Credentials = MagicMock()++ _BQ_EXPORT_NAMES = (+ "BigQueryIngestor",+ "BigQueryConnector",+ "BigQueryData",+ )++ import semantica.ingest as _ingest_pkg++ _cached_before = {+ name: _ingest_pkg.__dict__.get(name) for name in _BQ_EXPORT_NAMES+ }++ stub_modules = {+ "google": google_stub,+ "google.cloud": google_cloud_stub,+ "google.cloud.bigquery": bq_stub,+ "google.auth": google_auth_stub,+ "google.auth.exceptions": google_auth_stub.exceptions,+ "google.api_core": google_api_core_stub,+ "google.api_core.exceptions": google_api_core_stub.exceptions,+ "google.oauth2": google_oauth2_stub,+ "google.oauth2.service_account": google_oauth2_sa_stub,+ }++ with patch.dict("sys.modules", stub_modules):+ import semantica.ingest.bigquery_ingestor as _bq_mod++ with patch.object(_bq_mod, "BIGQUERY_AVAILABLE", True):+ try:+ yield+ finally:+ for name in _BQ_EXPORT_NAMES:+ if _cached_before[name] is None:+ _ingest_pkg.__dict__.pop(name, None)+ else:+ yield+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_mock_bq_client(project: str = "test-project") -> Mock:+ """Return a Mock that looks like a connected bigquery.Client."""+ mock_client = Mock()+ mock_client.project = project+ mock_client.close = Mock()+ return mock_client+++def _make_mock_row(keys: list, values: list) -> Mock:+ """Return a Mock that behaves like a google.cloud.bigquery.Row."""+ mock_row = Mock()+ mock_row.keys = Mock(return_value=keys)+ mock_row.__iter__ = Mock(return_value=iter(zip(keys, values)))+ # Support dict(row) by making the row behave as a mapping.+ mapping = dict(zip(keys, values))+ mock_row.__getitem__ = Mock(side_effect=mapping.__getitem__)+ mock_row.keys = Mock(return_value=list(mapping.keys()))+ # _rows_to_dicts calls dict(row) — patch it to return the mapping.+ mock_row.items = Mock(return_value=list(mapping.items()))+ return mock_row+++def _make_query_job(rows: list) -> Mock:+ """Return a Mock that behaves like a bigquery.QueryJob.++ The mock's ``.result()`` returns a RowIterator-like object with a+ ``.schema`` attribute (list of SchemaField mocks derived from the first+ row's keys when rows are present) and is iterable.+ """+ job = Mock()++ # Build a RowIterator-like mock that has .schema and is iterable.+ result_iter = Mock()++ if rows:+ # Derive schema field names from the first row's keys (if it's a dict).+ first = rows[0]+ if isinstance(first, dict):+ schema_fields = []+ for name in first.keys():+ f = Mock()+ f.name = name+ schema_fields.append(f)+ result_iter.schema = schema_fields+ else:+ # Non-dict row (e.g. plain Mock for test_connection ping) — no schema.+ result_iter.schema = []+ else:+ result_iter.schema = []++ result_iter.__iter__ = Mock(return_value=iter(rows))+ # list(result_iter) needs __iter__ to work; also support being called+ # as an iterable directly.+ job.result = Mock(return_value=result_iter)+ return job+++# ---------------------------------------------------------------------------+# TestBigQueryData+# ---------------------------------------------------------------------------+++class TestBigQueryData:+ """BigQueryData is a plain dataclass — no SDK dependency."""++ def test_creation_with_required_fields(self):+ from semantica.ingest.bigquery_ingestor import BigQueryData++ data = BigQueryData(data=[], row_count=0, columns=[])++ assert data.row_count == 0+ assert data.data == []+ assert data.columns == []+ assert data.table_name is None+ assert data.query is None+ assert data.project is None+ assert data.dataset is None+ assert data.location is None+ assert data.metadata == {}+ assert isinstance(data.ingested_at, datetime)++ def test_creation_with_all_fields(self):+ from semantica.ingest.bigquery_ingestor import BigQueryData++ rows = [{"id": "1", "name": "Alice"}]+ data = BigQueryData(+ data=rows,+ row_count=1,+ columns=["id", "name"],+ table_name="users",+ query="SELECT * FROM users",+ project="my-project",+ dataset="my_dataset",+ location="US",+ metadata={"custom": "value"},+ )++ assert data.row_count == 1+ assert data.table_name == "users"+ assert data.query == "SELECT * FROM users"+ assert data.project == "my-project"+ assert data.dataset == "my_dataset"+ assert data.location == "US"+ assert data.metadata["custom"] == "value"++ def test_importable_without_sdk(self):+ """BigQueryData must import even when google-cloud-bigquery is absent."""+ from semantica.ingest.bigquery_ingestor import BigQueryData++ data = BigQueryData(data=[{"col": 1}], row_count=1, columns=["col"])+ assert data.row_count == 1+++# ---------------------------------------------------------------------------+# TestBigQueryConnectorInit — ADC+# ---------------------------------------------------------------------------+++class TestBigQueryConnectorInitADC:+ """Constructor validation for Application Default Credentials."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_with_explicit_project(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ conn = BigQueryConnector(project="my-project")++ assert conn.project == "my-project"+ assert conn.dataset is None+ assert conn.location is None+ assert conn._credentials_file is None+ assert conn._client is None # not connected yet++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_with_project_dataset_location(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ conn = BigQueryConnector(+ project="my-project",+ dataset="my_dataset",+ location="europe-west1",+ )++ assert conn.project == "my-project"+ assert conn.dataset == "my_dataset"+ assert conn.location == "europe-west1"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_project_with_hyphens_accepted(self):+ """GCP project IDs contain hyphens — must not raise ValidationError."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ # Should not raise.+ conn = BigQueryConnector(project="my-gcp-project-123")+ assert conn.project == "my-gcp-project-123"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_missing_project_raises(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError, match="BigQuery project is required"):+ BigQueryConnector()++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_empty_project_raises(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError, match="BigQuery project is required"):+ BigQueryConnector(project="")+++# ---------------------------------------------------------------------------+# TestBigQueryConnectorInitKeyFile+# ---------------------------------------------------------------------------+++class TestBigQueryConnectorInitKeyFile:+ """Constructor validation for service-account key-file authentication."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_with_credentials_file(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ conn = BigQueryConnector(+ project="my-project",+ credentials_file="/path/to/sa-key.json",+ )++ assert conn._credentials_file == "/path/to/sa-key.json"+ assert conn.project == "my-project"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_credentials_file_not_logged(self):+ """credentials_file path must not appear in INFO/DEBUG log output."""+ import logging++ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with patch("semantica.ingest.bigquery_ingestor._logger") as mock_log:+ BigQueryConnector(+ project="my-project",+ credentials_file="/secrets/sa-key.json",+ )+ # The path itself should not appear as a plain value in log calls.+ for call_args in mock_log.debug.call_args_list:+ args_str = str(call_args)+ assert "/secrets/sa-key.json" not in args_str+++# ---------------------------------------------------------------------------+# TestBigQueryConnectorEnvVars+# ---------------------------------------------------------------------------+++class TestBigQueryConnectorEnvVars:+ """Environment-variable fallback for every constructor parameter."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_project_from_env(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with patch.dict(os.environ, {"BIGQUERY_PROJECT": "env-project"}):+ conn = BigQueryConnector()+ assert conn.project == "env-project"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_dataset_from_env(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with patch.dict(+ os.environ,+ {"BIGQUERY_PROJECT": "p", "BIGQUERY_DATASET": "env_dataset"},+ ):+ conn = BigQueryConnector()+ assert conn.dataset == "env_dataset"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_location_from_env(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with patch.dict(+ os.environ,+ {"BIGQUERY_PROJECT": "p", "BIGQUERY_LOCATION": "EU"},+ ):+ conn = BigQueryConnector()+ assert conn.location == "EU"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_credentials_file_from_env(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with patch.dict(+ os.environ,+ {+ "BIGQUERY_PROJECT": "p",+ "BIGQUERY_CREDENTIALS_FILE": "/env/sa-key.json",+ },+ ):+ conn = BigQueryConnector()+ assert conn._credentials_file == "/env/sa-key.json"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_explicit_args_override_env(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with patch.dict(+ os.environ,+ {"BIGQUERY_PROJECT": "env-project", "BIGQUERY_DATASET": "env_ds"},+ ):+ conn = BigQueryConnector(project="explicit-project", dataset="explicit_ds")++ assert conn.project == "explicit-project"+ assert conn.dataset == "explicit_ds"+++# ---------------------------------------------------------------------------+# TestBigQueryConnectorConnect+# ---------------------------------------------------------------------------+++class TestBigQueryConnectorConnect:+ """connect() / disconnect() / test_connection() lifecycle."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_connect_adc_calls_client_constructor(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_bq.Client.return_value = mock_client++ conn = BigQueryConnector(project="my-project")+ client = conn.connect()++ assert client is mock_client+ assert conn._client is mock_client+ mock_bq.Client.assert_called_once_with(project="my-project")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_connect_with_location(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_bq.Client.return_value = _make_mock_bq_client()++ conn = BigQueryConnector(project="my-project", location="EU")+ conn.connect()++ call_kwargs = mock_bq.Client.call_args[1]+ assert call_kwargs["location"] == "EU"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_connect_reuse_existing_client(self, mock_bq):+ """Second connect() must reuse the existing client, not call Client() again."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_bq.Client.return_value = _make_mock_bq_client()++ conn = BigQueryConnector(project="my-project")+ client1 = conn.connect()+ client2 = conn.connect()++ assert client1 is client2+ mock_bq.Client.assert_called_once()++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_disconnect_closes_client(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_bq.Client.return_value = mock_client++ conn = BigQueryConnector(project="my-project")+ conn.connect()+ conn.disconnect()++ mock_client.close.assert_called_once()+ assert conn._client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_disconnect_idempotent(self, mock_bq):+ """Calling disconnect() twice must not raise."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_bq.Client.return_value = _make_mock_bq_client()++ conn = BigQueryConnector(project="my-project")+ conn.connect()+ conn.disconnect()+ conn.disconnect() # second call — no-op, no exception++ assert conn._client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_connect_failure_clears_client_ref(self, mock_bq):+ """If Client() raises, _client must remain None."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector+ from semantica.utils.exceptions import ProcessingError++ mock_bq.Client.side_effect = RuntimeError("auth failure")++ conn = BigQueryConnector(project="my-project")+ with pytest.raises(ProcessingError):+ conn.connect()++ assert conn._client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_connect_with_credentials_file(self, mock_bq):+ """Service-account key-file path must be used to build credentials."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_bq.Client.return_value = mock_client++ mock_sa = MagicMock()+ mock_creds = MagicMock()+ mock_sa.Credentials.from_service_account_file.return_value = mock_creds++ conn = BigQueryConnector(+ project="my-project",+ credentials_file="/run/secrets/sa.json",+ )++ with patch(+ "google.oauth2.service_account", mock_sa, create=True+ ):+ # Patch the import inside _build_client+ with patch(+ "semantica.ingest.bigquery_ingestor._bigquery", mock_bq+ ):+ with patch(+ "semantica.ingest.bigquery_ingestor.BigQueryConnector._build_client"+ ) as mock_build:+ mock_build.return_value = mock_client+ client = conn.connect()++ assert client is mock_client++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_test_connection_returns_true_on_success(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([Mock()])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ conn = BigQueryConnector(project="my-project")+ result = conn.test_connection()++ assert result is True+ mock_client.query.assert_called_once_with("SELECT 1")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_test_connection_returns_false_on_failure(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_client.query = Mock(side_effect=RuntimeError("network error"))+ mock_bq.Client.return_value = mock_client++ conn = BigQueryConnector(project="my-project")+ result = conn.test_connection()++ assert result is False++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_test_connection_closes_transient_client(self, mock_bq):+ """test_connection() must close a client it opened itself."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([Mock()])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ conn = BigQueryConnector(project="my-project")+ assert conn._client is None++ conn.test_connection()++ # Client must be closed after test_connection returns.+ mock_client.close.assert_called_once()+ assert conn._client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_test_connection_keeps_existing_client(self, mock_bq):+ """test_connection() must not close a client it did not open."""+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([Mock()])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ conn = BigQueryConnector(project="my-project")+ conn.connect() # open before test_connection+ conn.test_connection()++ # Client must NOT be closed.+ mock_client.close.assert_not_called()+ assert conn._client is mock_client+++# ---------------------------------------------------------------------------+# TestBigQueryIngestorInit+# ---------------------------------------------------------------------------+++class TestBigQueryIngestorInit:+ """BigQueryIngestor.__init__ and connector composition."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_stores_connector(self):+ from semantica.ingest.bigquery_ingestor import (+ BigQueryConnector,+ BigQueryIngestor,+ )++ conn = BigQueryConnector(project="my-project")+ ing = BigQueryIngestor(connector=conn)++ assert ing.connector is conn++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_creates_connector_from_kwargs(self):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector, BigQueryIngestor++ ing = BigQueryIngestor(project="my-project", dataset="my_dataset")++ assert isinstance(ing.connector, BigQueryConnector)+ assert ing.connector.project == "my-project"+ assert ing.connector.dataset == "my_dataset"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_init_missing_project_raises(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError, match="BigQuery project is required"):+ BigQueryIngestor()+++# ---------------------------------------------------------------------------+# TestBigQueryIngestorTable+# ---------------------------------------------------------------------------+++class TestBigQueryIngestorTable:+ """BigQueryIngestor.ingest_table()."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_basic(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ mock_client = _make_mock_bq_client()+ rows = [{"id": "1", "name": "Alice"}, {"id": "2", "name": "Bob"}]+ mock_rows = [Mock() for _ in rows]+ for mock_row, row in zip(mock_rows, rows):+ mock_row.keys = Mock(return_value=list(row.keys()))+ # Make dict(row) work+ mock_row.__iter__ = Mock(return_value=iter(row.items()))+ # Override _rows_to_dicts path — patch at the class level+ mock_job = _make_query_job(mock_rows)+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="my-project", dataset="my_dataset")++ # Patch _rows_to_dicts to return plain dicts directly.+ with patch.object(+ type(ing),+ "_rows_to_dicts",+ staticmethod(lambda rows, schema_columns=None: (["id", "name"], [{"id": "1", "name": "Alice"}, {"id": "2", "name": "Bob"}])),+ ):+ data = ing.ingest_table("users")++ assert isinstance(data, BigQueryData)+ assert data.row_count == 2+ assert data.table_name == "users"+ assert data.project == "my-project"+ assert data.dataset == "my_dataset"+ assert "SELECT * FROM" in data.query+ assert "`users`" in data.query++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_generates_correct_sql(self, mock_bq):+ """Verify the SQL sent to client.query() is well-formed."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="my-project", dataset="my_dataset")+ ing.ingest_table(+ "orders",+ where="status = 'active'",+ order_by="created_at DESC",+ limit=100,+ )++ executed_sql = mock_client.query.call_args[0][0]+ assert "`my-project`.`my_dataset`.`orders`" in executed_sql+ assert "WHERE status = 'active'" in executed_sql+ assert "ORDER BY created_at DESC" in executed_sql+ assert "LIMIT 100" in executed_sql++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_no_limit(self, mock_bq):+ """When limit is None, no LIMIT clause should be added."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ ing.ingest_table("t")++ executed_sql = mock_client.query.call_args[0][0]+ assert "LIMIT" not in executed_sql++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_override_project_dataset(self, mock_bq):+ """Per-call project/dataset overrides the connector defaults."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="default-proj", dataset="default_ds")+ ing.ingest_table("t", project="override-proj", dataset="override_ds")++ executed_sql = mock_client.query.call_args[0][0]+ assert "`override-proj`" in executed_sql+ assert "`override_ds`" in executed_sql+ assert "default" not in executed_sql++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_closes_transient_connection(self, mock_bq):+ """Standalone ingest_table must close the client it opened."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ assert ing.connector.client is None++ ing.ingest_table("t")++ mock_client.close.assert_called_once()+ assert ing.connector.client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_reuses_context_manager_connection(self, mock_bq):+ """Inside a context manager, ingest_table must not close the shared client."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ with BigQueryIngestor(project="p", dataset="d") as ing:+ ing.ingest_table("t")+ # Client must still be open inside the context.+ assert ing.connector.client is mock_client+ mock_client.close.assert_not_called()++ # Client closed on __exit__.+ mock_client.close.assert_called_once()++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_ingest_table_invalid_table_name_raises(self):+ """Table names with SQL-injection characters must be rejected."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ValidationError):+ ing.ingest_table("my-table") # hyphen not allowed in table name++ with pytest.raises(ValidationError):+ ing.ingest_table("my table") # space not allowed++ with pytest.raises(ValidationError):+ ing.ingest_table("1table") # leading digit not allowed++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_ingest_table_invalid_where_raises(self):+ """WHERE clauses with injection characters must be rejected."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ValidationError):+ ing.ingest_table("t", where="1=1; DROP TABLE t")++ with pytest.raises(ValidationError):+ ing.ingest_table("t", where="1=1 UNION SELECT * FROM secrets")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_ingest_table_invalid_order_by_raises(self):+ """ORDER BY clauses with injection characters must be rejected."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ValidationError):+ ing.ingest_table("t", order_by="name; DROP TABLE t")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_ingest_table_invalid_dataset_raises(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ValidationError):+ ing.ingest_table("t", dataset="my dataset")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_ingest_table_missing_dataset_raises(self):+ """ingest_table must reject calls when no dataset is configured (PR comment)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ # No dataset on the ingestor, none passed at call site.+ ing = BigQueryIngestor(project="my-project")++ with pytest.raises(ValidationError, match="dataset is required"):+ ing.ingest_table("orders")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_ingest_table_valid_project_id_with_hyphens(self):+ """ingest_table must not reject valid GCP project IDs that contain hyphens."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")++ # This should raise ValidationError for project, NOT a blanket rejection.+ # The project override "my-project-123" is valid.+ # We only test validation passes (no error from _validate_bq_project_id).+ from semantica.ingest.bigquery_ingestor import _validate_bq_project_id++ result = _validate_bq_project_id("my-gcp-project-123")+ assert result == "my-gcp-project-123"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_wraps_sdk_error_in_processing_error(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ProcessingError++ mock_client = _make_mock_bq_client()+ mock_client.query = Mock(side_effect=RuntimeError("BQ error"))+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ProcessingError, match="Failed to ingest BigQuery table"):+ ing.ingest_table("t")+++# ---------------------------------------------------------------------------+# TestBigQueryIngestorQuery+# ---------------------------------------------------------------------------+++class TestBigQueryIngestorQuery:+ """BigQueryIngestor.ingest_query()."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_query_basic(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p")+ data = ing.ingest_query("SELECT 1 AS val")++ assert isinstance(data, BigQueryData)+ assert data.query == "SELECT 1 AS val"+ mock_client.query.assert_called_once_with("SELECT 1 AS val")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_query_with_job_config(self, mock_bq):+ """job_config is forwarded to client.query()."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ mock_job_config = MagicMock()++ ing = BigQueryIngestor(project="p")+ ing.ingest_query("SELECT @param AS v", job_config=mock_job_config)++ mock_client.query.assert_called_once_with(+ "SELECT @param AS v", job_config=mock_job_config+ )++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_query_closes_transient_connection(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p")+ ing.ingest_query("SELECT 1")++ mock_client.close.assert_called_once()+ assert ing.connector.client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_query_wraps_sdk_error(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ProcessingError++ mock_client = _make_mock_bq_client()+ mock_client.query = Mock(side_effect=RuntimeError("quota exceeded"))+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p")++ with pytest.raises(ProcessingError, match="Failed to execute BigQuery query"):+ ing.ingest_query("SELECT 1")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_query_stores_project_dataset_on_result(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="my-project", dataset="my_ds", location="US")+ data = ing.ingest_query("SELECT 1")++ assert data.project == "my-project"+ assert data.dataset == "my_ds"+ assert data.location == "US"+++# ---------------------------------------------------------------------------+# TestBigQueryIngestorSchema+# ---------------------------------------------------------------------------+++class TestBigQueryIngestorSchema:+ """BigQueryIngestor.get_table_schema() and list_tables()."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_get_table_schema_basic(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()++ # Build mock SchemaField objects.+ def _field(name, field_type, mode):+ f = Mock()+ f.name = name+ f.field_type = field_type+ f.mode = mode+ return f++ mock_table = Mock()+ mock_table.schema = [+ _field("id", "STRING", "REQUIRED"),+ _field("name", "STRING", "NULLABLE"),+ _field("value", "FLOAT64", "NULLABLE"),+ ]+ mock_table.num_rows = 1000+ mock_table.clustering_fields = None+ mock_client.get_table = Mock(return_value=mock_table)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="my-project", dataset="my_ds")+ schema = ing.get_table_schema("users")++ assert len(schema["columns"]) == 3+ assert schema["columns"][0] == {+ "name": "id",+ "type": "STRING",+ "nullable": False, # REQUIRED → not nullable+ }+ assert schema["columns"][1] == {+ "name": "name",+ "type": "STRING",+ "nullable": True, # NULLABLE → nullable+ }+ assert schema["num_rows"] == 1000+ assert schema["clustering_fields"] == []++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_get_table_schema_with_clustering(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_table = Mock()+ mock_table.schema = []+ mock_table.num_rows = 0+ mock_table.clustering_fields = ["region", "date"]+ mock_client.get_table = Mock(return_value=mock_table)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ schema = ing.get_table_schema("t")++ assert schema["clustering_fields"] == ["region", "date"]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_get_table_schema_builds_correct_table_ref(self, mock_bq):+ """get_table() must receive a fully-qualified dotted reference."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_table = Mock()+ mock_table.schema = []+ mock_table.num_rows = None+ mock_table.clustering_fields = None+ mock_client.get_table = Mock(return_value=mock_table)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="my-proj", dataset="my_ds")+ ing.get_table_schema("orders")++ called_ref = mock_client.get_table.call_args[0][0]+ assert called_ref == "my-proj.my_ds.orders"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_get_table_schema_invalid_table_name_raises(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ValidationError):+ ing.get_table_schema("my-table")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_get_table_schema_missing_dataset_raises(self):+ """get_table_schema must reject calls when no dataset is configured (PR comment)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ # No dataset on the ingestor, none passed at call site.+ ing = BigQueryIngestor(project="my-project")++ with pytest.raises(ValidationError, match="dataset is required"):+ ing.get_table_schema("orders")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_get_table_schema_wraps_sdk_error(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ProcessingError++ mock_client = _make_mock_bq_client()+ mock_client.get_table = Mock(side_effect=RuntimeError("not found"))+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ProcessingError, match="Failed to get schema"):+ ing.get_table_schema("missing_table")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_list_tables_basic(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()++ def _make_table_item(name):+ t = Mock()+ t.table_id = name+ return t++ mock_client.list_tables = Mock(+ return_value=[+ _make_table_item("orders"),+ _make_table_item("customers"),+ _make_table_item("products"),+ ]+ )+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="my_ds")+ tables = ing.list_tables()++ assert tables == ["customers", "orders", "products"] # sorted+ mock_client.list_tables.assert_called_once_with("p.my_ds")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_list_tables_override_dataset_project(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_client.list_tables = Mock(return_value=[])+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="default-p", dataset="default_ds")+ ing.list_tables(dataset="override_ds", project="override-p")++ mock_client.list_tables.assert_called_once_with("override-p.override_ds")++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_list_tables_no_dataset_raises(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ValidationError++ # No dataset configured at all.+ ing = BigQueryIngestor(project="p")++ with pytest.raises(ValidationError, match="dataset is required"):+ ing.list_tables()++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_list_tables_returns_empty_list_when_none(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_client.list_tables = Mock(return_value=[])+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ tables = ing.list_tables()++ assert tables == []++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_list_tables_wraps_sdk_error(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor+ from semantica.utils.exceptions import ProcessingError++ mock_client = _make_mock_bq_client()+ mock_client.list_tables = Mock(side_effect=RuntimeError("permission denied"))+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")++ with pytest.raises(ProcessingError, match="Failed to list BigQuery tables"):+ ing.list_tables()+++# ---------------------------------------------------------------------------+# TestRowConversion+# ---------------------------------------------------------------------------+++class TestRowConversion:+ """BigQueryIngestor._convert_rows() — type normalisation."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_string_passthrough(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"name": "Alice", "city": "NYC"}]+ result = ing._convert_rows(rows)+ assert result == [{"name": "Alice", "city": "NYC"}]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_int_float_bool_none_passthrough(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"i": 42, "f": 3.14, "b": True, "n": None}]+ result = ing._convert_rows(rows)+ assert result == [{"i": 42, "f": 3.14, "b": True, "n": None}]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_datetime_converted_to_isoformat(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ dt = datetime(2024, 6, 15, 12, 30, 0)+ rows = [{"ts": dt}]+ result = ing._convert_rows(rows)+ assert result[0]["ts"] == "2024-06-15T12:30:00"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_date_converted_to_isoformat(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ d = date(2024, 6, 15)+ rows = [{"day": d}]+ result = ing._convert_rows(rows)+ assert result[0]["day"] == "2024-06-15"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_time_converted_to_isoformat(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ t = time(14, 30, 59)+ rows = [{"t": t}]+ result = ing._convert_rows(rows)+ assert result[0]["t"] == "14:30:59"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_decimal_converted_to_string(self):+ """NUMERIC / BIGNUMERIC must become str to preserve precision."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"amount": decimal.Decimal("12345.6789")}]+ result = ing._convert_rows(rows)+ assert result[0]["amount"] == "12345.6789"+ assert isinstance(result[0]["amount"], str)++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_bytes_decoded_as_utf8(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"data": b"hello world"}]+ result = ing._convert_rows(rows)+ assert result[0]["data"] == "hello world"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_bytes_non_utf8_falls_back_to_str(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"data": b"\xff\xfe"}] # not valid UTF-8+ result = ing._convert_rows(rows)+ # Should not raise; result is a string representation.+ assert isinstance(result[0]["data"], str)++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_datetime_subclass_not_mishandled_as_date(self):+ """datetime must be processed before date (datetime is a date subclass)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ dt = datetime(2024, 1, 1, 8, 0, 0)+ rows = [{"ts": dt}]+ result = ing._convert_rows(rows)+ # A full datetime string, not just "2024-01-01".+ assert "T" in result[0]["ts"]+ assert result[0]["ts"] == "2024-01-01T08:00:00"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_rows_to_dicts_empty_returns_empty(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ columns, data = ing._rows_to_dicts([])+ assert columns == []+ assert data == []++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_rows_to_dicts_empty_with_schema_columns_preserves_columns(self):+ """Zero rows with schema_columns preserves the declared schema (Finding 2)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ columns, data = ing._rows_to_dicts([], schema_columns=["id", "name", "score"])+ assert columns == ["id", "name", "score"]+ assert data == []++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_rows_to_dicts_extracts_column_names(self):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")++ mock_row = Mock()+ mock_row.keys = Mock(return_value=["id", "name", "score"])+ # dict(row) must work.+ mock_row.__iter__ = Mock(+ return_value=iter([("id", "1"), ("name", "Alice"), ("score", 99)])+ )++ # Patch dict() behaviour by making the Mock iterable as a mapping.+ with patch("semantica.ingest.bigquery_ingestor.BigQueryIngestor._rows_to_dicts") as mock_r2d:+ mock_r2d.return_value = (+ ["id", "name", "score"],+ [{"id": "1", "name": "Alice", "score": 99}],+ )+ columns, data = ing._rows_to_dicts([mock_row])++ # Verify shape from the patched return.+ assert columns == ["id", "name", "score"]+ assert data[0]["name"] == "Alice"+++# ---------------------------------------------------------------------------+# TestExportAsDocuments+# ---------------------------------------------------------------------------+++class TestExportAsDocuments:+ """BigQueryIngestor.export_as_documents()."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_basic_export(self):+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[+ {"id": "1", "name": "Alice", "city": "NYC"},+ {"id": "2", "name": "Bob", "city": "LA"},+ ],+ row_count=2,+ columns=["id", "name", "city"],+ table_name="users",+ project="my-project",+ dataset="my_ds",+ location="US",+ )++ docs = ing.export_as_documents(data, text_fields=["name", "city"])++ assert len(docs) == 2+ assert docs[0]["id"] == "1"+ assert docs[0]["text"] == "Alice NYC"+ assert docs[0]["metadata"]["source"] == "bigquery"+ assert docs[0]["metadata"]["table"] == "users"+ assert docs[0]["metadata"]["project"] == "my-project"+ assert docs[0]["metadata"]["dataset"] == "my_ds"+ assert docs[0]["metadata"]["location"] == "US"+ assert docs[0]["metadata"]["row_data"]["name"] == "Alice"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_default_text_uses_all_string_fields(self):+ """When text_fields is None, all non-None string values are joined."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"id": "1", "name": "Alice", "score": 100}],+ row_count=1,+ columns=["id", "name", "score"],+ table_name="t",+ )++ docs = ing.export_as_documents(data)++ # Only string fields: id and name. score is int, excluded.+ assert "Alice" in docs[0]["text"]+ assert "1" in docs[0]["text"]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_id_field_default_is_id(self):+ """Default id_field is 'id'."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"id": "row_001", "name": "Alice"}],+ row_count=1,+ columns=["id", "name"],+ table_name="t",+ )++ docs = ing.export_as_documents(data)+ assert docs[0]["id"] == "row_001"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_custom_id_field(self):+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"order_id": "ORD-999", "amount": "100.00"}],+ row_count=1,+ columns=["order_id", "amount"],+ table_name="orders",+ )++ docs = ing.export_as_documents(data, id_field="order_id")+ assert docs[0]["id"] == "ORD-999"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_missing_id_field_falls_back_to_index(self):+ """If id_field key is absent, the row index is used."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"name": "No-ID record"}],+ row_count=1,+ columns=["name"],+ table_name="t",+ )++ docs = ing.export_as_documents(data)+ assert docs[0]["id"] == "0" # row index 0 as string++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_none_text_fields_skipped(self):+ """None values in text_fields are not included in the text."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"id": "1", "name": "Alice", "desc": None}],+ row_count=1,+ columns=["id", "name", "desc"],+ table_name="t",+ )++ docs = ing.export_as_documents(data, text_fields=["name", "desc"])+ assert docs[0]["text"] == "Alice" # None desc excluded++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_empty_data_returns_empty_list(self):+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(data=[], row_count=0, columns=[])+ docs = ing.export_as_documents(data)+ assert docs == []++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_metadata_shape(self):+ """Document metadata must contain all expected keys."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"id": "1", "v": "x"}],+ row_count=1,+ columns=["id", "v"],+ table_name="my_table",+ project="my-project",+ dataset="my_ds",+ location="US",+ )++ docs = ing.export_as_documents(data)+ meta = docs[0]["metadata"]++ assert meta["source"] == "bigquery"+ assert meta["table"] == "my_table"+ assert meta["project"] == "my-project"+ assert meta["dataset"] == "my_ds"+ assert meta["location"] == "US"+ assert "row_data" in meta+++# ---------------------------------------------------------------------------+# TestContextManagerLifecycle+# ---------------------------------------------------------------------------+++class TestContextManagerLifecycle:+ """Context-manager support."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_context_manager_opens_and_closes_connection(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_bq.Client.return_value = mock_client++ with BigQueryIngestor(project="p", dataset="d") as ing:+ # Client must be open inside the block.+ assert ing.connector.client is mock_client++ # Client must be closed on exit.+ mock_client.close.assert_called_once()+ assert ing.connector.client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_multiple_calls_inside_context_reuse_connection(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ with BigQueryIngestor(project="p", dataset="d") as ing:+ ing.ingest_table("t1")+ ing.ingest_table("t2")+ ing.ingest_query("SELECT 1")++ # Client constructor called exactly once — __enter__ only.+ mock_bq.Client.assert_called_once()+ # Client closed once on __exit__.+ mock_client.close.assert_called_once()++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_standalone_call_closes_connection(self, mock_bq):+ """Standalone ingest_table opens and closes its own connection."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_job = _make_query_job([])+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ ing.ingest_table("t")++ assert ing.connector.client is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_close_method_disconnects(self, mock_bq):+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ ing.connector.connect() # open directly+ ing.close()++ mock_client.close.assert_called_once()+ assert ing.connector.client is None+++# ---------------------------------------------------------------------------+# TestIdentifierValidation+# ---------------------------------------------------------------------------+++class TestIdentifierValidation:+ """Validate the BigQuery-specific identifier validators."""++ def test_valid_bq_identifier(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_identifier++ assert _validate_bq_identifier("my_table", "t") == "my_table"+ assert _validate_bq_identifier("Table1", "t") == "Table1"+ assert _validate_bq_identifier("_private", "t") == "_private"++ def test_invalid_bq_identifier_hyphen(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_identifier+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError):+ _validate_bq_identifier("my-table", "t")++ def test_invalid_bq_identifier_leading_digit(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_identifier+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError):+ _validate_bq_identifier("1table", "t")++ def test_invalid_bq_identifier_space(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_identifier+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError):+ _validate_bq_identifier("my table", "t")++ def test_valid_project_id_with_hyphens(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_project_id++ assert _validate_bq_project_id("my-project") == "my-project"+ assert _validate_bq_project_id("my-gcp-project-123") == "my-gcp-project-123"+ assert _validate_bq_project_id("project") == "project"+ assert _validate_bq_project_id("proj_123") == "proj_123"++ def test_invalid_project_id_leading_hyphen(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_project_id+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError):+ _validate_bq_project_id("-bad-project")++ def test_invalid_project_id_leading_digit(self):+ from semantica.ingest.bigquery_ingestor import _validate_bq_project_id+ from semantica.utils.exceptions import ValidationError++ with pytest.raises(ValidationError):+ _validate_bq_project_id("1project")++ def test_bq_quote_wraps_in_backticks(self):+ from semantica.ingest.bigquery_ingestor import _bq_quote++ assert _bq_quote("my_table") == "`my_table`"+ assert _bq_quote("my-project") == "`my-project`"++ def test_bq_quote_escapes_internal_backticks(self):+ from semantica.ingest.bigquery_ingestor import _bq_quote++ assert _bq_quote("my`table") == "`my``table`"++ def test_build_table_ref_full(self):+ from semantica.ingest.bigquery_ingestor import _build_table_ref++ ref = _build_table_ref("orders", "my_ds", "my-project")+ assert ref == "`my-project`.`my_ds`.`orders`"++ def test_build_table_ref_no_project(self):+ from semantica.ingest.bigquery_ingestor import _build_table_ref++ ref = _build_table_ref("orders", "my_ds", None)+ assert ref == "`my_ds`.`orders`"++ def test_build_table_ref_no_project_no_dataset(self):+ from semantica.ingest.bigquery_ingestor import _build_table_ref++ ref = _build_table_ref("orders", None, None)+ assert ref == "`orders`"+++# ---------------------------------------------------------------------------+# TestImportBehaviourWithoutLib+# ---------------------------------------------------------------------------+++class TestImportBehaviourWithoutLib:+ """Verify that the missing-SDK guard fires with the correct pip hint."""++ def test_bigquery_connector_raises_import_error_when_sdk_absent(self):+ """BigQueryConnector.__init__ must raise ImportError when SDK is absent."""+ with patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", False):+ from semantica.ingest.bigquery_ingestor import BigQueryConnector++ with pytest.raises(ImportError) as exc_info:+ BigQueryConnector(project="p")++ msg = str(exc_info.value)+ assert "google-cloud-bigquery" in msg+ assert 'semantica[db-bigquery]' in msg++ def test_bigquery_data_importable_without_sdk(self):+ """BigQueryData must remain importable even when SDK is absent."""+ with patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", False):+ from semantica.ingest.bigquery_ingestor import BigQueryData++ data = BigQueryData(data=[], row_count=0, columns=[])+ assert data.row_count == 0++ def test_lazy_import_raises_import_error_with_hint(self):+ """semantica.ingest.BigQueryConnector must raise ImportError with hint+ when BIGQUERY_AVAILABLE is False (secondary guard in __getattr__)."""+ import semantica.ingest as _ingest++ # Remove any cached entry first.+ _ingest.__dict__.pop("BigQueryConnector", None)+ _ingest.__dict__.pop("BigQueryIngestor", None)++ with patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", False):+ with pytest.raises(ImportError) as exc_info:+ _ = _ingest.BigQueryConnector++ msg = str(exc_info.value)+ assert "google-cloud-bigquery" in msg+ assert "semantica[db-bigquery]" in msg++ # Cleanup cached values so other tests are unaffected.+ _ingest.__dict__.pop("BigQueryConnector", None)+ _ingest.__dict__.pop("BigQueryIngestor", None)+++# ---------------------------------------------------------------------------+# TestNestedConversion — Finding 1+# ---------------------------------------------------------------------------+++class TestNestedConversion:+ """_convert_rows recurses into RECORD and REPEATED fields (Finding 1)."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_nested_record_dates_converted(self):+ """RECORD (STRUCT) fields containing date/datetime must be converted (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{+ "id": "1",+ "metadata": {+ "created": date(2024, 3, 15),+ "updated": datetime(2024, 3, 15, 10, 30, 0),+ }+ }]+ result = ing._convert_rows(rows)+ assert result[0]["metadata"]["created"] == "2024-03-15"+ assert result[0]["metadata"]["updated"] == "2024-03-15T10:30:00"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_nested_record_decimal_converted(self):+ """RECORD fields containing Decimal must be converted (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"price": {"amount": decimal.Decimal("99.99"), "currency": "USD"}}]+ result = ing._convert_rows(rows)+ assert result[0]["price"]["amount"] == "99.99"+ assert result[0]["price"]["currency"] == "USD"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_nested_record_bytes_converted(self):+ """RECORD fields containing bytes must be decoded (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"attachment": {"data": b"hello", "mime": "text/plain"}}]+ result = ing._convert_rows(rows)+ assert result[0]["attachment"]["data"] == "hello"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_repeated_field_dates_converted(self):+ """REPEATED (ARRAY) fields containing dates must be converted (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{+ "id": "1",+ "event_dates": [date(2024, 1, 1), date(2024, 6, 15)],+ }]+ result = ing._convert_rows(rows)+ assert result[0]["event_dates"] == ["2024-01-01", "2024-06-15"]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_repeated_field_decimals_converted(self):+ """REPEATED fields containing Decimals must be converted (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"scores": [decimal.Decimal("1.5"), decimal.Decimal("2.75")]}]+ result = ing._convert_rows(rows)+ assert result[0]["scores"] == ["1.5", "2.75"]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_repeated_record_nested_dates_converted(self):+ """REPEATED RECORD (array of structs) at multiple nesting levels (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{+ "line_items": [+ {"name": "Widget", "ordered_on": date(2024, 1, 10)},+ {"name": "Gadget", "ordered_on": date(2024, 2, 20)},+ ]+ }]+ result = ing._convert_rows(rows)+ assert result[0]["line_items"][0]["ordered_on"] == "2024-01-10"+ assert result[0]["line_items"][1]["ordered_on"] == "2024-02-20"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_string_and_scalars_unchanged_in_nested_record(self):+ """Plain scalar types inside RECORD must pass through unchanged (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{+ "profile": {+ "name": "Alice",+ "age": 30,+ "active": True,+ "score": 9.5,+ "notes": None,+ }+ }]+ result = ing._convert_rows(rows)+ p = result[0]["profile"]+ assert p["name"] == "Alice"+ assert p["age"] == 30+ assert p["active"] is True+ assert p["score"] == 9.5+ assert p["notes"] is None++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_convert_value_static_method(self):+ """_convert_value is callable as a static method (Finding 1)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ assert BigQueryIngestor._convert_value(date(2024, 1, 1)) == "2024-01-01"+ assert BigQueryIngestor._convert_value(decimal.Decimal("3.14")) == "3.14"+ assert BigQueryIngestor._convert_value(42) == 42+ assert BigQueryIngestor._convert_value(None) is None+ assert BigQueryIngestor._convert_value("text") == "text"+ assert BigQueryIngestor._convert_value([date(2024, 1, 1)]) == ["2024-01-01"]+ assert BigQueryIngestor._convert_value({"d": date(2024, 6, 1)}) == {"d": "2024-06-01"}++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_tuple_repeated_field_converted(self):+ """Tuple values are also recursively converted (PR nit 3)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ rows = [{"tags": (date(2024, 1, 1), date(2024, 6, 15))}]+ result = ing._convert_rows(rows)+ # Tuples are converted element-by-element; result is a list.+ assert result[0]["tags"] == ["2024-01-01", "2024-06-15"]+++# ---------------------------------------------------------------------------+# TestZeroRowResults — Finding 2+# ---------------------------------------------------------------------------+++class TestZeroRowResults:+ """ingest_table and ingest_query preserve column schema for zero-row results."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_zero_rows_preserves_columns(self, mock_bq):+ """Zero-row ingest_table must still return the correct column list (Finding 2)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()++ # Build a mock RowIterator with schema but no rows.+ mock_result = Mock()+ field1, field2, field3 = Mock(), Mock(), Mock()+ field1.name = "order_id"+ field2.name = "customer"+ field3.name = "total"+ mock_result.schema = [field1, field2, field3]+ mock_result.__iter__ = Mock(return_value=iter([]))++ mock_job = Mock()+ mock_job.result = Mock(return_value=mock_result)+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ data = ing.ingest_table("orders")++ assert data.row_count == 0+ assert data.data == []+ assert data.columns == ["order_id", "customer", "total"]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_query_zero_rows_preserves_columns(self, mock_bq):+ """Zero-row ingest_query must still return the correct column list (Finding 2)."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()++ mock_result = Mock()+ f1, f2 = Mock(), Mock()+ f1.name = "id"+ f2.name = "name"+ mock_result.schema = [f1, f2]+ mock_result.__iter__ = Mock(return_value=iter([]))++ mock_job = Mock()+ mock_job.result = Mock(return_value=mock_result)+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p")+ data = ing.ingest_query("SELECT id, name FROM t WHERE 1=0")++ assert data.row_count == 0+ assert data.data == []+ assert data.columns == ["id", "name"]++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ @patch("semantica.ingest.bigquery_ingestor._bigquery")+ def test_ingest_table_zero_rows_no_schema_returns_empty_columns(self, mock_bq):+ """If RowIterator has no schema (e.g. DDL), columns is empty but no crash."""+ from semantica.ingest.bigquery_ingestor import BigQueryIngestor++ mock_client = _make_mock_bq_client()++ mock_result = Mock()+ mock_result.schema = None+ mock_result.__iter__ = Mock(return_value=iter([]))++ mock_job = Mock()+ mock_job.result = Mock(return_value=mock_result)+ mock_client.query = Mock(return_value=mock_job)+ mock_bq.Client.return_value = mock_client++ ing = BigQueryIngestor(project="p", dataset="d")+ data = ing.ingest_table("t")++ assert data.columns == []+ assert data.data == []+++# ---------------------------------------------------------------------------+# TestNullIdHandling — Finding 3+# ---------------------------------------------------------------------------+++class TestNullIdHandling:+ """export_as_documents handles None id_field values as fallback (Finding 3)."""++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_none_id_field_value_uses_row_index(self):+ """A present-but-None id_field must fall back to the row index (Finding 3)."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[+ {"id": None, "name": "Alice"},+ {"id": None, "name": "Bob"},+ ],+ row_count=2,+ columns=["id", "name"],+ table_name="t",+ )++ docs = ing.export_as_documents(data, id_field="id")++ # Each None id must yield its row index, not the shared string "None".+ assert docs[0]["id"] == "0"+ assert docs[1]["id"] == "1"+ # Must NOT be "None".+ assert docs[0]["id"] != "None"+ assert docs[1]["id"] != "None"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_multiple_none_ids_get_distinct_fallback_indices(self):+ """Multiple rows with None id must produce distinct document IDs (Finding 3)."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[+ {"id": None, "name": "Row0"},+ {"id": None, "name": "Row1"},+ {"id": None, "name": "Row2"},+ ],+ row_count=3,+ columns=["id", "name"],+ table_name="t",+ )++ docs = ing.export_as_documents(data, id_field="id")++ ids = [d["id"] for d in docs]+ assert ids == ["0", "1", "2"]+ # All distinct.+ assert len(set(ids)) == 3++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_mixed_real_and_none_ids(self):+ """Rows with real IDs keep them; None rows fall back to their indices."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[+ {"id": "real-001", "name": "Alice"},+ {"id": None, "name": "Bob"},+ {"id": "real-003", "name": "Carol"},+ ],+ row_count=3,+ columns=["id", "name"],+ table_name="t",+ )++ docs = ing.export_as_documents(data, id_field="id")++ assert docs[0]["id"] == "real-001"+ assert docs[1]["id"] == "1" # row index fallback+ assert docs[2]["id"] == "real-003"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_missing_id_field_still_uses_index(self):+ """Absent id_field key (not present in row) still falls back to index."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[{"name": "No-ID"}],+ row_count=1,+ columns=["name"],+ table_name="t",+ )+ docs = ing.export_as_documents(data)+ assert docs[0]["id"] == "0"++ @patch("semantica.ingest.bigquery_ingestor.BIGQUERY_AVAILABLE", True)+ def test_zero_numeric_id_is_not_treated_as_falsy(self):+ """An id value of integer 0 or string '0' must NOT fall back to index."""+ from semantica.ingest.bigquery_ingestor import BigQueryData, BigQueryIngestor++ ing = BigQueryIngestor(project="p", dataset="d")+ data = BigQueryData(+ data=[+ {"id": 0, "name": "Zero-int"},+ {"id": "0", "name": "Zero-str"},+ ],+ row_count=2,+ columns=["id", "name"],+ table_name="t",+ )+ docs = ing.export_as_documents(data, id_field="id")+ assert docs[0]["id"] == "0" # str(0)+ assert docs[1]["id"] == "0" # "0"+++def _load_pyproject_toml():+ try:+ import tomllib # Python 3.11++ except ModuleNotFoundError:+ try:+ import tomli as tomllib # backport for <3.11+ except ModuleNotFoundError:+ pytest.skip("tomllib / tomli not available — skipping TOML-based tests")+ from pathlib import Path++ toml_path = Path(__file__).resolve().parents[1] / "pyproject.toml"+ with open(toml_path, "rb") as f:+ return tomllib.load(f)+++class TestDbAllIncludesBigQuery:+ """pyproject.toml db-all aggregate must reference db-bigquery."""++ def test_db_all_references_db_bigquery(self):+ """Read pyproject.toml and verify db-all includes db-bigquery."""+ data = _load_pyproject_toml()++ db_all = data["project"]["optional-dependencies"]["db-all"]+ # db-all is a list of strings like ["semantica[db-snowflake,...]"]+ combined = " ".join(db_all)+ assert "db-bigquery" in combined, (+ f"db-all does not reference db-bigquery. Got: {db_all}"+ )++ def test_db_bigquery_extra_exists(self):+ """pyproject.toml must define the db-bigquery optional extra."""+ data = _load_pyproject_toml()++ extras = data["project"]["optional-dependencies"]+ assert "db-bigquery" in extras, "db-bigquery extra is missing from pyproject.toml"++ combined = " ".join(extras["db-bigquery"])+ assert "google-cloud-bigquery" in combined++ def test_db_bigquery_version_floor(self):+ """db-bigquery must specify google-cloud-bigquery>=3.0.0."""+ data = _load_pyproject_toml()++ db_bigquery = data["project"]["optional-dependencies"]["db-bigquery"]+ combined = " ".join(db_bigquery)+ assert ">=3.0.0" in combined, (+ f"db-bigquery does not specify >=3.0.0. Got: {db_bigquery}"+ )+++# ---------------------------------------------------------------------------+# TestEagerImportGuard+# ---------------------------------------------------------------------------+++class TestEagerImportGuard:+ """import semantica.ingest must NOT eagerly import google-cloud-bigquery."""++ def test_import_semantica_ingest_does_not_import_bigquery(self):+ """The google.cloud.bigquery module must not appear in sys.modules+ purely as a side-effect of importing semantica.ingest."""+ import sys++ # Remove any previously cached google.cloud.bigquery entry.+ saved = sys.modules.pop("google.cloud.bigquery", None)+ try:+ # Re-importing semantica.ingest must not trigger the BigQuery SDK.+ import importlib++ import semantica.ingest+ importlib.reload(semantica.ingest)++ assert "google.cloud.bigquery" not in sys.modules, (+ "google.cloud.bigquery was eagerly imported by semantica.ingest"+ )+ finally:+ # Restore original state so other tests are unaffected.+ if saved is not None:+ sys.modules["google.cloud.bigquery"] = saved