# Chalk Python SDK Reference: SQL
source: https://docs.chalk.ai/api-docs#section-sql

## `AthenaSource(name, aws_region, aws_access_key_id, aws_access_key_secret, s3_staging_dir, catalog_name, schema_name, role_arn, work_group, engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#AthenaSource

Create an Amazon Athena data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details. DynamoDBSources can be queried via PartiQL SQL resolvers.

You may override the ambient AWS credentials by providing either a client ID and secret, or a role ARN.

**Overloads**

#### `AthenaSource(permission_tags)`

If you have only one Athena connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

#### `AthenaSource(name, engine_args, permission_tags)`

If you have only one Athena integration, there's no need to provide a distinguishing name. But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  The name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = AthenaSource(name="RISK")
```

#### `AthenaSource(name, aws_region, aws_access_key_id, aws_access_key_secret, s3_staging_dir, catalog_name, schema_name, role_arn, work_group, engine_args, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `None`
  The name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `aws_region`: `str | None` = `None`
  The AWS region code to connect to, such as `"us-east-1"`.
- `aws_access_key_id`: `str | None` = `None`
  Optionally override the credentials using an AWS client id, must be provided with a client secret override.
- `aws_access_key_secret`: `str | None` = `None`
  Optionally override the credentials using an AWS client secret, must be provided with a client id override.
- `s3_staging_dir`: `str | None` = `None`
  The query result location to store query results within s3.
- `catalog_name`: `str | None` = `None`
  The catalog name to query. Defaults to "awsdatacatalog".
- `schema_name`: `str | None` = `None`
  The schema (database) name to query. Defaults to "default".
- `role_arn`: `str | None` = `None`
  Optionally override the credentials using an AWS role ARN.
- `work_group`: `str | None` = `None`
  Optionally provide an Athena work group to query from.
- `engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = AthenaSource(name="RISK")
```

## `BigQuerySource(name, project, dataset, location, credentials_base64, credentials_path, engine_args, temp_project, temp_dataset, unload_path, permission_tags)`
source: https://docs.chalk.ai/api-docs#BigQuerySource

Create a BigQuery data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `BigQuerySource(permission_tags)`

If you have only one BigQuery connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = BigQuerySource()
```

#### `BigQuerySource(name, engine_args, unload_path, permission_tags)`

If you have only one BigQuery integration, there's no need to provide a distinguishing name.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `unload_path`: `str | None` = `...`
  GCS path to use for unload-based BigQuery execution.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = BigQuerySource(name="RISK")
```

#### `BigQuerySource(name, project, dataset, location, credentials_base64, credentials_path, engine_args, temp_project, temp_dataset, unload_path, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  Name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `project`: `str | None` = `...`
  The name of the GCP project for the BigQuery instance.
- `dataset`: `str | None` = `...`
  The name of the BigQuery dataset.
- `location`: `str | None` = `...`
  The location of the BigQuery instance.
- `credentials_base64`: `str | None` = `...`
  The credentials to use to connect, encoded as a base64 string.
- `credentials_path`: `str | None` = `...`
  The path to the credentials file to use to connect.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `temp_project`: `str | None` = `...`
  The BigQuery project to use for temporary tables.
- `temp_dataset`: `str | None` = `...`
  The BigQuery dataset to use for temporary tables.
- `unload_path`: `str | None` = `...`
  GCS path to use for unload-based BigQuery execution.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
source = BigQuerySource(
    project=os.getenv("BIGQUERY_PROJECT"),
    dataset=os.getenv("BIGQUERY_DATASET"),
    location=os.getenv("BIGQUERY_LOCATION"),
    credentials_base64=os.getenv("BIGQUERY_CREDENTIALS_BASE64"),
)
```

## `CloudSQLSource(name, instance_name, db, user, password, engine_args, async_engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#CloudSQLSource

Create a CloudSQL data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `CloudSQLSource(permission_tags)`

If you have only one CloudSQL connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = CloudSQLSource()
```

#### `CloudSQLSource(name, engine_args, async_engine_args, permission_tags)`

If you have only one CloudSQL integration, there's no need to provide a distinguishing name.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `async_engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = CloudSQLSource(name="RISK")
```

#### `CloudSQLSource(name, instance_name, db, user, password, engine_args, async_engine_args, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  Name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `instance_name`: `str | None` = `...`
  The name of the Cloud SQL instance, as defined in your GCP console.
- `db`: `str | None` = `...`
  Database to use.
- `user`: `str | None` = `...`
  Username to use.
- `password`: `str | None` = `...`
  The password to use.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `async_engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
CloudSQLSource(
    instance_name=os.getenv("CLOUDSQL_INSTANCE_NAME"),
    db=os.getenv("CLOUDSQL_DB"),
    user=os.getenv("CLOUDSQL_USER"),
    password=os.getenv("CLOUDSQL_PASSWORD"),
)
```

## `DatabricksSource(name, host, http_path, access_token, db, port, client_id, client_secret, engine_args, permission_tags, temp_catalog, temp_schema)`
source: https://docs.chalk.ai/api-docs#DatabricksSource

Create a Databricks data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `DatabricksSource(permission_tags)`

Connect to the only configured Databricks data source.

If you have only one Databricks connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = DatabricksSource()
```

#### `DatabricksSource(name, engine_args, permission_tags)`

Chalk's injects environment variables to support data integrations.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = DatabricksSource(name="RISK")
```

#### `DatabricksSource(name, host, http_path, access_token, db, port, client_id, client_secret, engine_args, permission_tags, temp_catalog, temp_schema)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  Name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `host`: `str` = `...`
  Your Databricks host.
- `http_path`: `str` = `...`
  Databricks HTTP path to use.
- `access_token`: `str` = `...`
  Access token to connect to Databricks.
- `db`: `str` = `...`
  Initial Databricks catalog. Schemas (also called databases in Databricks SQL) are a separate namespace level.
- `port`: `str` = `...`
  Port number to use.
- `client_id`: `str` = `...`
  OAuth service principal client ID (alternative to access_token).
- `client_secret`: `str` = `...`
  OAuth service principal client secret (alternative to access_token).
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`
- `temp_catalog`: `str | None` = `...`
  Catalog for the staging tables Chalk creates when a resolver is queried with too many input keys to inline in the SQL. Defaults to `db`. Only used when `temp_schema` is set.
- `temp_schema`: `str | None` = `...`
  Schema for those staging tables, e.g. a Chalk-owned schema separate from your warehouse data. The integration's principal needs `CREATE TABLE` on it. When unset, staging tables are created in the session's current schema.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
databricks = DatabricksSource(
    host=os.getenv("DATABRICKS_HOST"),
    http_path=os.getenv("DATABRICKS_HTTP_PATH"),
    access_token=os.getenv("DATABRICKS_TOKEN"),
    db=os.getenv("DATABRICKS_DATABASE"),
    port=os.getenv("DATABRICKS_PORT"),
)
databricks_with_oauth = DatabricksSource(
    host=os.getenv("DATABRICKS_HOST"),
    http_path=os.getenv("DATABRICKS_HTTP_PATH"),
    client_id=os.getenv("DATABRICKS_CLIENT_ID"),
    client_secret=os.getenv("DATABRICKS_CLIENT_SECRET"),
    db=os.getenv("DATABRICKS_DATABASE"),
    port=os.getenv("DATABRICKS_PORT"),
)
```

## `DynamoDBSource(name, aws_client_id_override, aws_client_secret_override, aws_role_arn_override, aws_region_override, endpoint_override, engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#DynamoDBSource

Create a DynamoDB data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details. DynamoDBSources can be queried via PartiQL SQL resolvers.

You may override the ambient AWS credentials by providing either a client ID and secret, or a role ARN.

**Overloads**

#### `DynamoDBSource(permission_tags)`

If you have only one DynamoDB connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

#### `DynamoDBSource(name, engine_args, permission_tags)`

If you have only one DynamoDB integration, there's no need to provide a distinguishing name. But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  The name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = DynamoDBSource(name="RISK")
```

#### `DynamoDBSource(name, aws_client_id_override, aws_client_secret_override, aws_role_arn_override, aws_region_override, endpoint_override, engine_args, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `None`
  The name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `aws_client_id_override`: `str | None` = `None`
  Optionally override the credentials using an AWS client id, must be provided with a client secret override.
- `aws_client_secret_override`: `str | None` = `None`
  Optionally override the credentials using an AWS client secret, must be provided with a client id override.
- `aws_role_arn_override`: `str | None` = `None`
  Optionally override the credentials using an AWS role ARN.
- `aws_region_override`: `str | None` = `None`
  The AWS region code to connect to, such as `"us-east-1"`.
- `endpoint_override`: `str | None` = `None`
  Override for the DynamoDB endpoint if hosted elsewhere.
- `engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = DynamoDBSource(name="RISK")
```

## `MySQLSource(host, port, db, user, password, name, engine_args, async_engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#MySQLSource

Create a MySQL data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `MySQLSource(permission_tags)`

If you have only one MySQL connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
mysql = MySQLSource()
```

#### `MySQLSource(name, engine_args, async_engine_args, permission_tags)`

If you have only one MySQL integration, there's no need to provide a distinguishing name.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `async_engine_args`: `dict[str, Any] | None` = `...`
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = MySQLSource(name="RISK")
```

#### `MySQLSource(name, host, port, db, user, password, engine_args, async_engine_args, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  Name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `host`: `str`
  Name of host to connect to.
- `port`: `int | str` = `...`
  The port number to connect to at the server host.
- `db`: `str` = `...`
  The database name.
- `user`: `str` = `...`
  MySQL username to connect as.
- `password`: `str` = `...`
  The password to be used if the server demands password authentication.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `async_engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
mysql = MySQLSource(
    host=os.getenv("PGHOST"),
    port=os.getenv("PGPORT"),
    db=os.getenv("PGDATABASE"),
    user=os.getenv("PGUSER"),
    password=os.getenv("PGPASSWORD"),
)
from chalk.features import online
@online
def resolver_fn() -> User.name:
    return mysql.query_string("select name from users where id = 4").one()
```

## `PostgreSQLSource(host, port, db, user, password, name, engine_args, async_engine_args, permission_tags, aws_iam_auth, aws_region, aws_role_arn)`
source: https://docs.chalk.ai/api-docs#PostgreSQLSource

Create a PostgreSQL data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `PostgreSQLSource(permission_tags)`

Connect to the only configured PostgreSQL database.

If you have only one PostgreSQL connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
pg = PostgreSQLSource()
```

#### `PostgreSQLSource(name, engine_args, async_engine_args, permission_tags)`

If you have only one PostgreSQL integration, there's no need to provide a distinguishing name.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `async_engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = PostgreSQLSource(name="RISK")
```

#### `PostgreSQLSource(name, host, port, db, user, password, engine_args, async_engine_args, permission_tags, aws_iam_auth, aws_region, aws_role_arn)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  Name of the integration. Not required unless if this PostgresSQLSource is used within SQL File Resolvers.
- `host`: `str | None` = `...`
  Name of host to connect to.
- `port`: `int | str | None` = `...`
  The port number to connect to at the server host.
- `db`: `str | None` = `...`
  The database name.
- `user`: `str | None` = `...`
  PostgreSQL username to connect as.
- `password`: `str | None` = `...`
  The password to be used if the server demands password authentication.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `async_engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`
- `aws_iam_auth`: `bool | str | None` = `...`
  Authenticate to Amazon RDS with IAM instead of a password. Chalk mints a short-lived auth token for each connection, so no password is stored. The database user must have been granted `rds_iam`, and Chalk's IAM principal needs `rds-db:connect` on it. RDS requires TLS for IAM connections, so Chalk defaults `connect_args["sslmode"]` to `"require"`; set `sslmode` explicitly in `engine_args["connect_args"]` to override.
- `aws_region`: `str | None` = `...`
  AWS region of the RDS instance, used when signing IAM auth tokens. Defaults to the ambient AWS configuration chain. Only used when `aws_iam_auth` is set.
- `aws_role_arn`: `str | None` = `...`
  Optional IAM role to assume before signing IAM auth tokens, for cross-account access. Only used when `aws_iam_auth` is set.

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
pg = PostgreSQLSource(
    host=os.getenv("PGHOST"),
    port=os.getenv("PGPORT"),
    db=os.getenv("PGDATABASE"),
    user=os.getenv("PGUSER"),
    password=os.getenv("PGPASSWORD"),
)
from chalk.features import online
@online
def resolver_fn() -> User.name:
    return pg.query_string("select name from users where id = 4").one()
```

## `RedshiftSource(host, db, user, password, name, port, engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#RedshiftSource

Create a Redshift data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `RedshiftSource(permission_tags)`

If you have only one Redshift connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = RedshiftSource()
```

#### `RedshiftSource(name, engine_args, permission_tags)`

If you have only one Redshift integration, there's no need to provide a distinguishing name.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = RedshiftSource(name="RISK")
```

#### `RedshiftSource(name, host, db, user, password, port, engine_args, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  The name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `host`: `str` = `...`
  Name of host to connect to.
- `db`: `str` = `...`
  The database name.
- `user`: `str` = `...`
  Redshify username to connect as.
- `password`: `str` = `...`
  The password for the Redshift database.
- `port`: `str` = `...`
  The port number to use.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
redshift = RedshiftSource(
    host=os.getenv("REDSHIFT_HOST"),
    db=os.getenv("REDSHIFT_DB"),
    user=os.getenv("REDSHIFT_USER"),
    password=os.getenv("REDSHIFT_PASSWORD"),
)
from chalk.features import online
@online
def resolver_fn() -> User.name:
    return redshift.query_string("select name from users where id = 4").one()
```

## `SnowflakeSource(name, account_identifier, warehouse, user, password, db, schema, role, private_key_b64, unload_stage, unload_storage_integration, unload_external_location, engine_args, permission_tags, warehouse_by_resource_group)`
source: https://docs.chalk.ai/api-docs#SnowflakeSource

Create a Snowflake data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `SnowflakeSource(permission_tags)`

Connect to the only configured Snowflake database.

If you have only one Snowflake connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = SnowflakeSource()
```

#### `SnowflakeSource(name, engine_args, permission_tags, warehouse_by_resource_group)`

Chalk's injects environment variables to support data integrations.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `permission_tags`: `list[str] | None` = `...`
- `warehouse_by_resource_group`: `Mapping[str, str] | None` = `...`
  Mapping of resource group name to the Snowflake warehouse to use when running in that resource group. Resource groups not in the mapping use the default warehouse.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = SnowflakeSource(name="RISK")
```

#### `SnowflakeSource(name, account_identifier, warehouse, user, password, db, schema, role, private_key_b64, unload_stage, unload_storage_integration, unload_external_location, engine_args, permission_tags, warehouse_by_resource_group)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `...`
  Name of the integration. Not required unless if this PostgresSQLSource is used within SQL File Resolvers.
- `account_identifier`: `str | None` = `...`
  Your Snowflake account identifier.
- `warehouse`: `str` = `...`
  Snowflake warehouse to use.
- `user`: `str | None` = `...`
  Username to connect to Snowflake.
- `password`: `str | None` = `...`
  The password to use.
- `db`: `str | None` = `...`
  Database to use.
- `schema`: `str | None` = `...`
  Snowflake schema in the database to use.
- `role`: `str | None` = `...`
  Snowflake role name to use.
- `private_key_b64`: `str | None` = `...`
  Base64-encoded unencrypted PKCS#8 PEM private key (the entire file, including the `-----BEGIN PRIVATE KEY-----` and `-----END PRIVATE KEY-----` lines) for key-pair authentication. May also be supplied via the `SNOWFLAKE_PRIVATE_KEY_B64` environment variable. When set, key-pair authentication is used instead of `password`.
- `unload_stage`: `str | None` = `...`
  Snowflake stage or cloud storage prefix to use for unload-based execution.
- `unload_storage_integration`: `str | None` = `...`
  Snowflake storage integration to use when unloading to external cloud storage.
- `unload_external_location`: `str | None` = `...`
  External cloud resource (i.e. "s3://...", "gs://...") that the unloaded Snowflake query will be located. Should be equal to unload_stage if unload_stage is itself a cloud resource, or should be the location equal to DESCRIBE  if unload_stage is a Snowflake stage.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`
- `warehouse_by_resource_group`: `Mapping[str, str] | None` = `...`
  Mapping of resource group name to the Snowflake warehouse to use when running in that resource group. Resource groups not in the mapping use the default warehouse.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
snowflake = SnowflakeSource(
    db=os.getenv("SNOWSQL_DATABASE"),
    schema=os.getenv("SNOWSQL_SCHEMA"),
    role=os.getenv("SNOWSQL_ROLE"),
    warehouse=os.getenv("SNOWSQL_WAREHOUSE"),
    user=os.getenv("SNOWSQL_USER"),
    password=os.getenv("SNOWSQL_PWD"),
    account_identifier=os.getenv("SNOWSQL_ACCOUNT_IDENTIFIER")
)
```

## `SpannerSource(name, project, instance, database, credentials_base64, emulator_host, engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#SpannerSource

Create a Spanner data source. SQL-based data sources created without arguments assume a configuration in your [Chalk Dashboard](https://chalk.ai/projects). Those created with the `name=` keyword argument will use the configuration for the integration with the given name. And finally, those created with explicit arguments will use those arguments to configure the data source. See the overloaded signatures for more details.

**Overloads**

#### `SpannerSource(permission_tags)`

If you have only one Spanner connection that you'd like to add to Chalk, you do not need to specify any arguments to construct the source in your code.

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = SpannerSource()
```

#### `SpannerSource(name, engine_args, permission_tags)`

If you have only one Spanner integration, there's no need to provide a distinguishing name.

But what happens when you have two data sources of the same kind? When you create a new data source from your dashboard, you have an option to provide a name for the integration. You can then reference this name in the code directly.

**Parameters**

- `name`: `str`
  Name of the integration, as configured in your dashboard.
- `engine_args`: `dict[str, Any] | None` = `...`
  Additional arguments to use when constructing the SQLAlchemy engine. These arguments will be merged with any default arguments from the named integration.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = SpannerSource(name="RISK")
```

#### `SpannerSource(name, project, instance, database, credentials_base64, emulator_host, engine_args, permission_tags)`

You can also configure the integration directly using environment variables on your local machine or from those added through the generic environment variable support ([Secrets and Engine Configuration Variables](https://docs.chalk.ai/docs/env-vars)).

**Parameters**

- `name`: `str | None` = `None`
  Name of the integration. Not required unless if this SQL Source is used within SQL File Resolvers.
- `project`: `str | None` = `None`
  The name of the GCP project for the Spanner instance.
- `instance`: `str | None` = `None`
  The name of the Spanner instance.
- `database`: `str | None` = `None`
  The name of the database in the Spanner instance.
- `credentials_base64`: `str | None` = `None`
  The credentials to use to connect, encoded as a base64 string.
- `emulator_host`: `str | None` = `None`
  Location of Spanner emulator, if desired.
- `engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `...`

**Returns**

`BaseSQLSourceProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
import os
source = SpannerSource(
    project=os.getenv("SPANNER_PROJECT"),
    instance=os.getenv("SPANNER_INSTANCE"),
    database=os.getenv("SPANNER_DATABASE"),
    credentials_base64=os.getenv("SPANNER_CREDENTIALS_BASE64"),
)
```

## `SQLiteFileSource(filename, name, engine_args, async_engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#SQLiteFileSource

Create a SQLite source for a file.

**Parameters**

- `filename`: `str | PathLike`
  The name of the file.
- `name`: `str | None` = `None`
  The name to use in testing
- `engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `async_engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `None`

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

## `SQLiteInMemorySource(name, engine_args, async_engine_args, permission_tags)`
source: https://docs.chalk.ai/api-docs#SQLiteInMemorySource

Testing SQL source.

If you have only one SQLiteInMemorySource integration, there's no need to provide a distinguishing name.

**Parameters**

- `name`: `str | None` = `None`
  The name of the integration.
- `engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing the SQLAlchemy engine.
- `async_engine_args`: `dict[str, Any] | None` = `None`
  Additional arguments to use when constructing an async SQLAlchemy engine.
- `permission_tags`: `list[str] | None` = `None`

**Returns**

`SQLSourceWithTableIngestProtocol`

The SQL source for use in Chalk resolvers.

**Examples**

```python
source = SQLiteInMemorySource(name="RISK")
```

## `IncrementalSettings`
source: https://docs.chalk.ai/api-docs#IncrementalSettings

Class

Incremental settings for Chalk SQL queries.

In `"row"` mode: `incremental_column` MUST be set.

Returns the results represented by this query as a list (like `.all()`), but modifies the query to only return "new" results, by adding a clause that looks like:

```
``
"WHERE <incremental_column> >= <previous_latest_row_timestamp> - <lookback_period>"
``
```

In `"group"` mode: `incremental_column` MUST be set.

Returns the results represented by this query as a list (like `.all()`), but modifies the query to only results from "groups" which have changed since the last run of the query.

This works by (1) parsing your query, (2) finding the "group keys", (3) selecting only changed groups. Concretely:

```
``
SELECT user_id, sum(amount) as sum_amount
FROM payments
GROUP BY user_id
``
```

would be rewritten like this:

```
``
SELECT user_id, sum(amount) as sum_amount
FROM payments
WHERE user_id in (
    SELECT DISTINCT(user_id)
    FROM payments WHERE created_at >= <previous_latest_row_timestamp> - <lookback_period>
)
GROUP BY user_id
``
```

In "parameter" mode: `incremental_column` WILL BE IGNORED.

This mode is for cases where you want full control of incrementalization. Chalk will not manipulate your query. Chalk will include a query parameter named `"chalk_incremental_timestamp"`. Depending on your SQL dialect, you can use this value to incrementalize your query with `:chalk_incremental_timestamp` or `%(chalk_incremental_timestamp)s`. This will incrementalize your query using the timestamp of the latest row that has been ingested.

Chalk will also include another query parameter named `"chalk_last_execution_timestamp"` that can be used instead. This will incrementalize your query using the last time the query was executed.

incremental_timestamp:

If incremental_timestamp is "feature_time", we will incrementalize your query using the timestamp of the latest row that has been ingested. This is the default.

If incremental_timestamp is "resolver_execution_time", we will incrementalize your query using the last time the query was executed instead.

**Attributes**

- `mode`: `'row' | 'group' | 'parameter'`
- `lookback_period`: `timedelta | None`
  The amount of overlap to check for late-arriving rows.
- `incremental_column`: `str | None`
  The column on which to incrementalize.
- `incremental_timestamp`: `'feature_time' | 'resolver_execution_time'`
  The timestamp to set as the lower bound

## `BaseSQLSourceProtocol`
source: https://docs.chalk.ai/api-docs#BaseSQLSourceProtocol

Class (bases: `Protocol`)

**Attributes**

- `name`: `str | None`

### `BaseSQLSourceProtocol.raw_query(query, output_arrow_schema)`
source: https://docs.chalk.ai/api-docs#BaseSQLSourceProtocol.raw_query

Run a raw query and return the underlying result.

This is useful for running queries that do not map to features, or for running queries that return a different schema on each execution.

**Parameters**

- `query`: `str`
  The query that you'd like to run.
- `output_arrow_schema`: `Any | None` = `None`
  Optionally, the expected output schema of the query as a `pyarrow.Schema`. Some SQL sources require this value to interpret the results correctly.

**Returns**

`Any`

The raw result of executing the query. The type of this result depends on the SQL source.

### `BaseSQLSourceProtocol.query_string(query, fields, args)`
source: https://docs.chalk.ai/api-docs#BaseSQLSourceProtocol.query_string

Run a query from a SQL string.

**Parameters**

- `query`: `str`
  The query that you'd like to run.
- `fields`: `Mapping[str, Feature | str | Any] | None` = `None`
  A mapping from the column names selected to features.
- `args`: `Mapping[str, object] | None` = `None`
  Any args in the sql string specified by `query` need to have corresponding value assignments in `args`.

**Returns**

`StringChalkQueryProtocol`

A query that can be returned from a [`@online`](https://docs.chalk.ai/api-docs#online) or [`@offline`](https://docs.chalk.ai/api-docs#offline) resolver.

### `BaseSQLSourceProtocol.query_sql_file(path, fields, args)`
source: https://docs.chalk.ai/api-docs#BaseSQLSourceProtocol.query_sql_file

Run a query from a SQL file.

This method allows you to query the SQL file within a Python resolver. However, Chalk can also infer resolvers from SQL files. See [SQL file resolvers](https://docs.chalk.ai/docs/sql#sql-file-resolvers) for more information.

**Parameters**

- `path`: `str | bytes | PathLike`
  The path to the file with the sql file, relative to the caller's file, or to the directory that your `chalk.yaml` file lives in.
- `fields`: `Mapping[str, Feature | str | Any] | None` = `None`
  A mapping from the column names selected to features.
- `args`: `Mapping[str, object] | None` = `None`
  Any args in the sql file specified by `path` need to have corresponding value assignments in `args`.

**Returns**

`StringChalkQueryProtocol`

A query that can be returned from a [`@online`](https://docs.chalk.ai/api-docs#online) or [`@offline`](https://docs.chalk.ai/api-docs#offline) resolver.

### `BaseSQLSourceProtocol.query(entities)`
source: https://docs.chalk.ai/api-docs#BaseSQLSourceProtocol.query

Query using a `SQLAlchemy` model.

**Parameters**

- `entities`: `Any` = `()`
  Arguments as would normally be passed to a `SQLAlchemy`.

**Returns**

`ChalkQueryProtocol`

A query that can be returned from a resolver.

### `BaseSQLSourceProtocol.get_engine()`
source: https://docs.chalk.ai/api-docs#BaseSQLSourceProtocol.get_engine

Get an SQLAlchemy Engine. The engine will be created and cached on the first call of this method.

**Returns**

`sqlalchemy.engine.Engine`

A SQLAlchemy engine.

## `SQLSourceWithTableIngestProtocol`
source: https://docs.chalk.ai/api-docs#SQLSourceWithTableIngestProtocol

Class (bases: `TableIngestProtocol`, `BaseSQLSourceProtocol`, `Protocol`)

## `TableIngestProtocol`
source: https://docs.chalk.ai/api-docs#TableIngestProtocol

Class (bases: `Protocol`)

### `TableIngestProtocol.with_table(name, features, ignore_columns, ignore_features, require_columns, require_features, column_to_feature, cdc)`
source: https://docs.chalk.ai/api-docs#TableIngestProtocol.with_table

Automatically ingest a table.

**Parameters**

- `name`: `str`
  The name of the table to ingest.
- `features`: `Type[Features | Any]`
  The feature class that this table should be mapping to, e.g. `User`.
- `ignore_columns`: `list[str] | None` = `None`
  Columns in the table that should be ignored, and not mapped to features, even if there is a matching name.
- `ignore_features`: `list[str | Any] | None` = `None`
  Features on the feature class that should be ignored, and not mapped to columns, even if there is a matching name.
- `require_columns`: `list[str] | None` = `None`
  Columns that must exist in the mapping.
- `require_features`: `list[str | Any] | None` = `None`
  Features that must exist in the mapping.
- `column_to_feature`: `dict[str, Any] | None` = `None`
  Explicit mapping of columns to features for names that do not match.
- `cdc`: `bool | IncrementalSettings | None` = `None`
  Settings for incrementally ingesting the table.

**Examples**

```python
from chalk.sql import PostgreSQLSource
from chalk.features import features
PostgreSQLSource().with_table(
    name="users",
    features=User,
).with_table(
    name="accounts",
    features=Account,
    # Override one of the column mappings.
    column_to_feature={
        "acct_id": Account.id,
    },
)
```

## `ChalkQueryProtocol`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol

Class (bases: `Protocol`)

### `ChalkQueryProtocol.first()`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.first

Return the first result of this Query or None if the result doesn't contain any row.

**Returns**

`SingletonFinalizedChalkQuery`

A query that can be returned from a resolver.

### `ChalkQueryProtocol.one_or_none()`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.one_or_none

Return at most one result or raise an exception.

Returns [`None`](https://docs.python.org/3/library/constants.html#None) if the query selects no rows. Raises if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

**Returns**

`SingletonFinalizedChalkQuery`

A query that can be returned from a resolver.

### `ChalkQueryProtocol.one()`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.one

Return exactly one result or raise an exception.

**Returns**

`SingletonFinalizedChalkQuery`

A query that can be returned from a resolver.

### `ChalkQueryProtocol.all()`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.all

Return the results represented by this Query as a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame).

**Returns**

`DataframeFinalizedChalkQuery`

A query that can be returned from a resolver.

### `ChalkQueryProtocol.incremental(lookback_period, mode, incremental_column, incremental_timestamp, params)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.incremental

Operates like `.all()`, but tracks `previous_latest_row_timestamp` between query executions in order to limit the amount of data returned.

`previous_latest_row_timestamp` will be set the start of the query execution, or if you return a `FeatureTime`-mapped column, Chalk will update `previous_latest_row_timestamp` to the maximum observed `FeatureTime` value.

In `"row"` mode: `incremental_column` MUST be set.

Returns the results represented by this query as a list (like `.all()`), but modifies the query to only return "new" results, by adding a clause that looks like:

```
``
WHERE <incremental_column> >= <previous_latest_row_timestamp> - <lookback_period>
``
```

In `"group"` mode: `incremental_column` MUST be set.

Returns the results represented by this query as a list (like `.all()`), but modifies the query to only results from "groups" which have changed since the last run of the query.

This works by (1) parsing your query, (2) finding the "group keys", (3) selecting only changed groups. Concretely:

```
``
SELECT user_id, sum(amount) as sum_amount
FROM payments
GROUP BY user_id
``
```

would be rewritten like this:

```
``
SELECT user_id, sum(amount) as sum_amount
FROM payments
WHERE user_id in (
    SELECT DISTINCT(user_id)
    FROM payments WHERE created_at >= <previous_latest_row_timestamp> - <lookback_period>
)
GROUP BY user_id
``
```

In `"parameter"` mode: `incremental_column` WILL BE IGNORED.

This mode is for cases where you want full control of incrementalization. Chalk will not manipulate your query. Chalk will include a query parameter named `"chalk_incremental_timestamp"`. Depending on your SQL dialect, you can use this value to incrementalize your query with `:chalk_incremental_timestamp` or `%(chalk_incremental_timestamp)s`.

**Parameters**

- `lookback_period`: `Duration` = `'0s'`
  Defaults to `0`, which means we only return rows that are strictly newer than the last observed row.
- `mode`: `'row' | 'group' | 'parameter'` = `'row'`
  Defaults to `"row"`, which indicates that only rows newer than the last observed row should be considered. When set to `"group"`, Chalk will only ingest features from groups which are newer than the last observation time. This requires that the query is grouped by a primary key.
- `incremental_column`: `str | Feature | None` = `None`
  This should reference a timestamp column in your underlying table, typically something like `"updated_at"`, `"created_at"`, `"event_time"`, etc.
- `incremental_timestamp`: `'feature_time' | 'resolver_execution_time'` = `'feature_time'`
  Defaults to `"feature_time"`, which means that the timestamp associated with the last feature value will be used as the incremental time. Alternatively, setting this parameter to `"resolver_execution_time"` will use last literal timestamp that the resolver ran.
- `params`: `Mapping[str, Any] | None` = `None`

**Returns**

`DataframeFinalizedChalkQuery`

A query that can be returned from a resolver.

### `ChalkQueryProtocol.filter_by(kwargs)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.filter_by

Apply the given filtering criterion to a copy of this Query, using keyword expressions.

**Parameters**

- `kwargs`: `Any` = `{}`
  The column names assigned to the desired values (i.e. `name="Maria"`).

**Returns**

`ChalkQueryProtocol`

A query that can be returned from a resolver or further filtered.

**Examples**

```python
from chalk.sql import PostgreSQLSource
session = PostgreSQLSource()
session.query(UserFeatures(id=UserSQL.id)).filter_by(name="Maria")
```

### `ChalkQueryProtocol.filter(criterion)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.filter

Apply the given filtering criterion to a copy of this Query, using SQL expressions.

**Parameters**

- `criterion`: `Any` = `()`
  SQLAlchemy filter criterion

**Returns**

`ChalkQueryProtocol`

A query that can be returned from a resolver or further filtered.

### `ChalkQueryProtocol.order_by(clauses)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.order_by

Apply one or more ORDER BY criteria to the query and return the newly resulting Query.

**Parameters**

- `clauses`: `Any` = `()`
  SQLAlchemy columns.

**Returns**

`ChalkQueryProtocol`

A query that can be returned from a resolver or further filtered.

### `ChalkQueryProtocol.group_by(clauses)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.group_by

### `ChalkQueryProtocol.having(criterion)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.having

### `ChalkQueryProtocol.union(q)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.union

### `ChalkQueryProtocol.union_all(q)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.union_all

### `ChalkQueryProtocol.intersect(q)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.intersect

### `ChalkQueryProtocol.intersect_all(q)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.intersect_all

### `ChalkQueryProtocol.join(target, props, kwargs)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.join

### `ChalkQueryProtocol.outerjoin(target, props, kwargs)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.outerjoin

### `ChalkQueryProtocol.select_from(from_obj)`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.select_from

### `ChalkQueryProtocol.execute()`
source: https://docs.chalk.ai/api-docs#ChalkQueryProtocol.execute

Materialize the query.

Chalk queries are lazy, which allows Chalk to perform performance optimizations like push-down filters. Instead of calling execute, consider returning this query from a resolver as an intermediate feature, and processing that intermediate feature in a different resolver.

Note: this requires the usage of the `fields={...}` argument when used in conjunction with `query_string` or `query_sql_file`.

**Returns**

The raw result of executing the query. For `.all()`, returns a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame). For `.one()` or `.one_or_none()`, returns a `Features` instance corresponding to the relevant feature class.

## `StringChalkQueryProtocol`
source: https://docs.chalk.ai/api-docs#StringChalkQueryProtocol

Class (bases: `Protocol`)

### `StringChalkQueryProtocol.execute()`
source: https://docs.chalk.ai/api-docs#StringChalkQueryProtocol.execute

Materialize the query.

Chalk queries are lazy, which allows Chalk to perform performance optimizations like push-down filters. Instead of calling execute, consider returning this query from a resolver as an intermediate feature, and processing that intermediate feature in a different resolver.

**Returns**

`DataFrame`

A [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame) with the results of the query.

### `StringChalkQueryProtocol.one_or_none()`
source: https://docs.chalk.ai/api-docs#StringChalkQueryProtocol.one_or_none

Return at most one result or raise an exception.

Returns [`None`](https://docs.python.org/3/library/constants.html#None) if the query selects no rows. Raises if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

**Returns**

`SingletonFinalizedChalkQuery`

A query that can be returned from a resolver.

### `StringChalkQueryProtocol.one()`
source: https://docs.chalk.ai/api-docs#StringChalkQueryProtocol.one

Return exactly one result or raise an exception.

**Returns**

`SingletonFinalizedChalkQuery`

A query that can be returned from a resolver.

### `StringChalkQueryProtocol.all()`
source: https://docs.chalk.ai/api-docs#StringChalkQueryProtocol.all

Return the results represented by this Query as a list.

**Returns**

`DataframeFinalizedChalkQuery`

A query that can be returned from a resolver.

### `StringChalkQueryProtocol.incremental(incremental_column, lookback_period, mode, incremental_timestamp)`
source: https://docs.chalk.ai/api-docs#StringChalkQueryProtocol.incremental

Operates like `.all()`, but tracks `previous_latest_row_timestamp` between query executions in order to limit the amount of data returned.

`previous_latest_row_timestamp` will be set the start of the query execution, or if you return a `FeatureTime`-mapped column, Chalk will update `previous_latest_row_timestamp` to the maximum observed `FeatureTime` value.

In `"row"` mode: `incremental_column` MUST be set.

Returns the results represented by this query as a list (like `.all()`), but modifies the query to only return "new" results, by adding a clause that looks like:

```
``
WHERE <incremental_column> >= <previous_latest_row_timestamp> - <lookback_period>
``
```

In `"group"` mode: `incremental_column` MUST be set.

Returns the results represented by this query as a list (like `.all()`), but modifies the query to only results from "groups" which have changed since the last run of the query.

This works by (1) parsing your query, (2) finding the "group keys", (3) selecting only changed groups. Concretely:

```
``
SELECT user_id, sum(amount) as sum_amount
FROM payments
GROUP BY user_id
``
```

would be rewritten like this:

```
``
SELECT user_id, sum(amount) as sum_amount
FROM payments
WHERE user_id in (
    SELECT DISTINCT(user_id)
    FROM payments WHERE created_at >= <previous_latest_row_timestamp> - <lookback_period>
)
GROUP BY user_id
``
```

In `"parameter"` mode: `incremental_column` WILL BE IGNORED.

This mode is for cases where you want full control of incrementalization. Chalk will not manipulate your query. Chalk will include a query parameter named `"chalk_incremental_timestamp"`. Depending on your SQL dialect, you can use this value to incrementalize your query with `:chalk_incremental_timestamp` or `%(chalk_incremental_timestamp)s`.

**Parameters**

- `incremental_column`: `str | None` = `None`
  This should reference a timestamp column in your underlying table, typically something like `"updated_at"`, `"created_at"`, `"event_time"`, etc.
- `lookback_period`: `Duration | None` = `'0s'`
  Defaults to `0`, which means we only return rows that are strictly newer than the last observed row.
- `mode`: `'row' | 'group' | 'parameter'` = `'row'`
  Defaults to `"row"`, which indicates that only rows newer than the last observed row should be considered. When set to `"group"`, Chalk will only ingest features from groups which are newer than the last observation time. This requires that the query is grouped by a primary key.
- `incremental_timestamp`: `'feature_time' | 'resolver_execution_time'` = `'feature_time'`
  Defaults to `"feature_time"`, which means that the timestamp associated with the last feature value will be used as the incremental time. Alternatively, setting this parameter to `"resolver_execution_time"` will use last literal timestamp that the resolver ran.

**Returns**

`DataframeFinalizedChalkQuery`

A query that can be returned from a resolver.

## `make_sql_file_resolver(name, sql, source, resolves, kind, postprocessing_expression, incremental, count, timeout, cron, owner, machine_type, fields, field_types, environment, tags, unique_on, partitioned_by, total, skip_sql_validation, handle_duplicate_outputs, use_native_sql, retry_policy, max_row_version_lookback)`
source: https://docs.chalk.ai/api-docs#make_sql_file_resolver

Generate a Chalk SQL file resolver from a filepath and a sql string. This will generate a resolver in your web dashboard that can be queried, but will not output a `.chalk.sql` file.

The optional parameters are overrides for the comment key-value pairs at the top of the sql file resolver. Comment key-value pairs specify important resolver information such as the source, feature namespace to resolve, and other details. Note that these will override any values specified in the sql string. See [Configuration](https://docs.chalk.ai/docs/sql#configuration) for more information.

See [SQL file resolvers](https://docs.chalk.ai/docs/sql#sql-file-resolvers) for more information on SQL file resolvers.

**Parameters**

- `name`: `str`
  The name of your resolver
- `sql`: `str`
  The sql string for your query.
- `source`: `str | BaseSQLSourceProtocol | None` = `None`
  Can either be a BaseSQLSource or a string. If a string is provided, it will be used to infer the source by first scanning for a source with the same name, then inferring the source if it is a type, e.g. `snowflake` if there is only one database of that type. Optional if `source` is specified in `sql`. The reserved name `"chalksql"` binds no integration at all: the query is written in Chalk SQL and compiled into the query plan by the Chalk engine.
- `resolves`: `str | Any | None` = `None`
  Describes the feature namespace to which the outputs belong. Optional if `resolves` is specified in `sql`.
- `kind`: `'online' | 'offline' | 'streaming' | None` = `None`
  The type of resolver. If not specified, defaults to "online".
- `postprocessing_expression`: `Underscore | None` = `None`

**Other parameters**

- `incremental`: `IncrementalSettings | None` = `None`
  Parameters for incremental queries. For more information, see [Incremental queries](https://docs.chalk.ai/docs/sql#incremental-queries).
- `count`: `1 | 'one' | 'one_or_none' | 'all' | None` = `None`
  If set to `one`, the resolver will return only one row. If set to `one_or_none`, the resolver will return at most one row. If set to `all`, the resolver will return all rows
- `timeout`: `Duration | None` = `None`
  You can specify the maximum duration to wait for the resolver's result. Once the resolver's runtime exceeds the specified duration, a timeout error will be returned along with each output feature.

  Please use supported Chalk durations 'w', 'd', 'h', 'm', 's', and/or 'ms'.

  Read more at [Timeout](https://docs.chalk.ai/docs/timeout) and https://docs.chalk.ai/api-docs#Duration
- `cron`: `CronTab | Duration | Cron | None` = `None`
  You can schedule resolvers to run on a pre-determined schedule via the cron argument to resolver decorators.

  Cron can sample all examples, a subset of all examples, or a custom provided set of examples.

  Read more at [Scheduling](https://docs.chalk.ai/docs/resolver-cron)
- `owner`: `str | None` = `None`
  Individual or team responsible for this resolver. The [Chalk Dashboard](https://chalk.ai/projects) will display this field, and alerts can be routed to owners.
- `machine_type`: `MachineType | None` = `None`
  You can optionally specify that resolvers need to run on a machine other than the default. Must be configured in your deployment.
- `fields`: `dict[str, str | FeatureReference] | None` = `None`
  An optional mapping from SQL column to Chalk feature. For example, let's say we have a Chalk feature class 'Transaction' with a primary key 'id'. If we have a SQL query like `SELECT txn_id from transactions`, we can map the `txn_id` to our Chalk feature with the mapping `txn_id: id`.
- `field_types`: `dict[str, str] | None` = `None`
  An optional mapping from SQL column to database-specific type. Used to generate CAST expressions for query parameters to ensure proper type matching. For example, `field_types={"user_id": "uuid"}` will wrap parameters for the `user_id` column with `CAST($1 AS uuid)` in PostgreSQL or `CAST(? AS uuid)` in MySQL. This is particularly useful for database types that don't auto-cast from text, such as PostgreSQL's UUID, INET, or MySQL's BINARY types.
- `environment`: `Environments | None` = `None`
  Environments are used to trigger behavior in different deployments such as staging, production, and local development. For example, you may wish to interact with a vendor via an API call in the production environment, and opt to return a constant value in a staging environment.

  Environment can take one of three types:

  - [`None`](https://docs.python.org/3/library/constants.html#None) (default) - candidate to run in every environment
  - [`str`](https://docs.python.org/3/library/stdtypes.html#str) - run only in this environment
  - `list[str]` - run in any of the specified environment and no others

  Read more at [Environments](https://docs.chalk.ai/docs/resolver-environments)
- `tags`: `Tags | None` = `None`
  Allow you to scope requests within an environment. Both tags and environment need to match for a resolver to be a candidate to execute.

  You might consider using tags, for example, to change out whether you want to use a sandbox environment for a vendor, or to bypass the vendor and return constant values in a staging environment.

  Read more at [Routing tags](https://docs.chalk.ai/docs/resolver-tags)
- `unique_on`: `Collection[FeatureReference] | None` = `None`
  A list of features that must be unique for each row of the output. This enables unique optimizations in the resolver execution. Only applicable to resolvers that return a DataFrame.
- `partitioned_by`: `Collection[Any] | None` = `None`
  A list of features that correspond to partition keys in the data source. This field indicates that this resolver executes its query against a data storage system that is partitioned by a particular set of columns. This is most common with data-warehouse sources like Snowflake, BigQuery or Databricks.
- `total`: `bool | None` = `None`
  Whether this resolver returns all ids of a given namespace. To have this annotation, the resolver must take no arguments and return a DataFrame.
- `skip_sql_validation`: `bool | None` = `None`
  If set to [`True`](https://docs.python.org/3/library/constants.html#True), skips sqlglot validation of the SQL query. This is useful when the SQL contains database-specific syntax that sqlglot cannot parse. When validation is skipped, you must provide the `fields` parameter to explicitly map SQL columns to Chalk features.
- `handle_duplicate_outputs`: `str | None` = `None`
  Controls how this resolver handles duplicate primary-key rows in its output. Overrides the server-wide `DEFAULT_HANDLE_DUPLICATE_OUTPUTS` setting for this resolver only.

  Accepted values:

  - `"skip_validation"` — do not check for duplicates.
  - `"dedup_any"` — deduplicate by selecting one row and dropping all others silently.
  - `"error"` — raise an error if any primary-key value appears more than once.

  If [`None`](https://docs.python.org/3/library/constants.html#None) (the default), the server-wide default is used.
- `use_native_sql`: `bool | None` = `None`
  If set to not None, overrides whether this resolver uses native sql during execution. When set to [`True`](https://docs.python.org/3/library/constants.html#True), will always run with native sql if the dialect is supported. When set to [`False`](https://docs.python.org/3/library/constants.html#False), will never run with native sql.
- `retry_policy`: `SQLResolverRetryPolicy | None` = `None`
  Conditions under which the resolver re-runs its query. Set `if_not_found` to re-run a query that returned no rows (for a resolver reading a store that may not yet reflect a recent write) and/or `if_timeout` to re-run a query that failed with a server-side statement timeout, each backing off exponentially. Only honored by the native SQL operator.
- `max_row_version_lookback`: `Duration | None` = `None`
  Asserts that for any observation time `t`, if a key has any row at or before `t`, then the most recent such row is at or after `t - max_row_version_lookback`. Set this on a resolver reading a CDC or snapshot table to let Chalk bound the query's feature time from below, instead of scanning all history to find each key's latest version. Requires the resolver to select its namespace's `FeatureTime`. Chalk looks back exactly this far and adds no margin, so include any tolerable delay in the pipeline that populates the table.

**Examples**

```python
from chalk import make_sql_file_resolver
from chalk.features import features
@features
class User:
    id: int
    name: str
make_sql_file_resolver(
    name="my_resolver",
    sql="SELECT user_id as id, name FROM users",
    source="snowflake",
    resolves=User,
    kind="offline",
)
```
