> ## Documentation Index
> Fetch the complete documentation index at: https://docs.validio.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Update a Source Schema

> Re-infer and update a source schema programmatically, verifying changes that may affect segmentations, windows, or validators.

## Overview

Re-infer the schema for a source, and update the source with the new schema. Before updating, verify the new schema to spot any changes that affect segmentations, windows, or validators.

## Steps

**1. Create the entry point**

Import the required modules and create an entry point that takes the `source_id` of the source whose JTD schema you want to update.

**2. Create a function to get the schema**

Create a function that accepts a client, a credential for authentication, and the project, dataset, and table to infer the schema for. In the later steps, these values come from the source itself.

**3. Create a function to verify the schema**

Write a function that accepts a source ID and a schema, so you can verify the schema before updating the source. The verification ensures that the new schema doesn't affect any current segmentations, windows, or validators.

**4. Get the source config**

Create a function that accepts a client and the source to update the JTD schema for. Start by fetching the current source config. The credential ID, project, dataset, and table are needed to re-infer the schema.

**5. Infer the schema**

Call the `get_jtd_schema` function with the credential and configuration of the source. This returns the current JTD schema for the source.

**6. Update the source**

Pass the source ID and the new JTD schema to `sourceUpdate`. The source is now updated with the new JTD schema.

## Full code sample

```python title="Python" theme={null}
from typing import Any

from validio_sdk.client import Client


async def update_source_jtd_schema(source_id: str):
    client = Client()
    await update_bigquery_source_jtd_schema(client, source_id)

    print(f"Updated schema for source with id {source_id}")


async def get_jtd_schema(
    client: Client,
    credential_id: str,
    project: str,
    dataset: str,
    table: str,
) -> dict[str, Any]:
    query = """
    query GcpBigQueryInferSchema($input: GcpBigQueryInferSchemaInput!) {
      gcpBigQueryInferSchema(input: $input)
    }
    """
    variable_values = {
        "input": {
            "credentialId": credential_id,
            "project": project,
            "dataset": dataset,
            "table": table,
        }
    }

    result = await client.execute(
        query,
        variable_values=variable_values,
    )

    return result["gcpBigQueryInferSchema"]


async def verify_jtd_schema(
    client: Client,
    source_id: str,
    jtd_schema: dict[str, Any],
) -> None:
    mutation = """
    mutation SourceSchemaVerify($id: SourceId!, $input: JsonTypeDefinition!) {
      sourceSchemaVerify(id: $id, input: $input) {
        segmentationConflicts {
          fields
          segmentation { id }
        }
        validatorConflicts {
          fields
          validator { id }
        }
        windowConflicts {
          fields
          window { id }
        }
      }
    }
    """

    result = await client.execute(
        mutation,
        variable_values={
            "id": source_id,
            "input": jtd_schema,
        },
    )

    for conflict_type in [
        "segmentationConflicts",
        "validatorConflicts",
        "windowConflicts",
    ]:
        assert not result["sourceSchemaVerify"][
            conflict_type
        ], f"New schema is invalid for the current setup: {result}"


async def update_bigquery_source_jtd_schema(
    client: Client,
    source_id: str,
) -> None:
    source_query = """
    query Source($id: SourceId!) {
      source(id: $id) {
        credential {
          id
        }

        ... on GcpBigQuerySource {
          config {
            project
            dataset
            table
          }
        }
      }
    }
    """

    source = await client.execute(source_query, variable_values={"id": source_id})
    source_config = source["source"]["config"]

    jtd_schema = await get_jtd_schema(
        client,
        source["source"]["credential"]["id"],
        source_config["project"],
        source_config["dataset"],
        source_config["table"],
    )

    await verify_jtd_schema(client, source_id, jtd_schema)

    update_mutation = """
    mutation SourceUpdate($input: SourceUpdateInput!) {
      sourceUpdate(input: $input) {
        id
      }
    }
    """

    variable_values = {
        "input": {
            "id": source_id,
            "jtdSchema": jtd_schema,
        }
    }

    await client.execute(
        update_mutation,
        variable_values=variable_values,
    )
```
