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

# Snowflake

> Connect your Snowflake data warehouse as a source

## Step 1: locate your public key

Locate the public key provided to you. The public key will be a long string of text, loosely resembling the format: `MIIBI...<SHORTENED>...Xrw2nwIDAQAB`. You will register this public key on the Snowflake user you create in Step 2.

## Step 2: create role, user, and warehouse

> [!NOTE]
>
> To complete the following setup steps, you or a Snowflake admin on your team must have the `SECURITYADMIN` and `SYSADMIN` roles. To check your account for these roles, run `SHOW GRANTS TO USER <your_username>;` and review the `role` column.

**1. Review the setup script**

Review and make any changes to the following setup script. Update `database_name` and `schema_name` to point at the database and schema you want to read from, list the tables you want to sync in the grant statements, and paste the public key from Step 1 into `RSA_PUBLIC_KEY`.

```sql title="Setup script" icon="database" expandable theme={null}
begin;

-- create variables for user / role / warehouse
set user_name = 'TRANSFER_USER'; -- all letters must be uppercase
set role_name = 'TRANSFER_ROLE'; -- all letters must be uppercase
set warehouse_name = 'TRANSFER_WAREHOUSE'; -- all letters must be uppercase
set database_name = 'SOURCE_DATABASE'; -- all letters must be uppercase
set schema_name = 'SOURCE_SCHEMA'; -- all letters must be uppercase

-- change role to securityadmin for user / role steps
use role securityadmin;

-- create role for the transfer service
create role if not exists identifier($role_name);
grant role identifier($role_name) to role SYSADMIN; -- establish SYSADMIN as the parent of the new role. Note: this does not grant the access privileges of SYSADMIN to the new role.

-- create a user for the transfer service
create user if not exists identifier($user_name)
RSA_PUBLIC_KEY='MIIBIjANBgkqh...'; -- replace with the complete public key from Step 1

-- set default role and warehouse, and mark the user as a service account
alter user identifier($user_name) SET default_role = $role_name;
alter user identifier($user_name) SET default_warehouse = $warehouse_name;
alter user identifier($user_name) SET type = service;

grant role identifier($role_name) to user identifier($user_name);

-- change role to sysadmin for warehouse / database steps
use role sysadmin;

-- create a warehouse for the transfer service
create warehouse if not exists identifier($warehouse_name)
warehouse_size = xsmall
warehouse_type = standard
auto_suspend = 60
auto_resume = true
initially_suspended = true;

-- grant warehouse and database access to the transfer role
grant USAGE on warehouse identifier($warehouse_name) to role identifier($role_name);
grant USAGE on database identifier($database_name) to role identifier($role_name);

-- grant schema and table read access to the transfer role
use database identifier($database_name);
grant USAGE on schema identifier($schema_name) to role identifier($role_name);
grant SELECT on table identifier($schema_name || '.<TABLE_NAME_A>') to role identifier($role_name); -- repeat for each table you want to sync
grant SELECT on table identifier($schema_name || '.<TABLE_NAME_B>') to role identifier($role_name);

commit;
```

> [!NOTE]
>
> By default, this script creates a new warehouse. If you would prefer to use an existing warehouse, change the `warehouse_name` variable from `TRANSFER_WAREHOUSE` to the name of the warehouse to be shared.

> [!NOTE]
>
> To grant access to every table in the schema instead of listing tables individually, replace the per-table grants with a single grant on all tables in the schema.
>
> ```sql title="Grant all tables" icon="database" theme={null}
> grant SELECT on all tables in schema identifier($schema_name) to role identifier($role_name);
> ```

> [!TIP]
>
> If a timestamp column is required for change tracking, prefer a [row timestamp](https://docs.snowflake.com/en/user-guide/data-engineering/row-timestamps) recorded by Snowflake over an application `updated_at` timestamp.
>
> Ensure that timestamp values increase in commit order. **Why:** A row committed later with an older timestamp can be skipped. Row timestamps are set when each change is committed, while an application `updated_at` can be set before a slow transaction commits.
>
> If your table does not have one, optionally, you can enable row timestamps and expose `METADATA$ROW_LAST_COMMIT_TIME` through a view.
>
> This view must then be the resource you grant access to and configure imports for, rather than the base table.
>
> ```sql title="Create and grant view" icon="database" theme={null}
> ALTER TABLE <schema_name>.<table_name> SET ROW_TIMESTAMP = TRUE;
>
> CREATE VIEW <schema_name>.<table_name>_sync AS
> SELECT METADATA$ROW_LAST_COMMIT_TIME AS etl_modified_at, *
> FROM <schema_name>.<table_name>;
>
> GRANT SELECT ON VIEW <schema_name>.<table_name>_sync TO ROLE identifier($role_name);
> ```
>
> Enabling row timestamps requires the `OWNERSHIP` privilege on the table. Row timestamps are not supported on Iceberg, external, or hybrid tables.

**2. Run the script**

In the Snowflake interface, select the dropdown next to the **Run** button, and click **Run All**. This will run every query in the script at once. If successful, you will see `Statement executed successfully` in the query results.

## Step 3: configure the Snowflake access policy

If your Snowflake data warehouse is using Snowflake Access Policies, a new policy must be added to allow the static IP to read from the warehouse. Reach out to your contact for the static IP address to use.

**1. Review current network policies**

Run the following to check for existing IP safelists.

```sql title="Show network policies" icon="database" theme={null}
SHOW NETWORK POLICIES;
```

If there is no existing Snowflake network policy (the `SHOW` query returns no results), you can skip to Step 4. If there is an existing Snowflake network policy, you must alter the existing policy or create a new one to safelist the static IP address.

**2. Create a network policy**

Run the following to create a new network policy that safelists the static IP address.

```sql title="Create network policy" icon="database" theme={null}
CREATE NETWORK POLICY <transfer_service_policy_name> ALLOWED_IP_LIST = ('<static_ip>');
```

> [!WARNING]
>
> If you have no existing network policies and you create your first as part of this step, all other IPs outside of the `ALLOWED_IP_LIST` will be blocked. Snowflake does not allow setting a network policy that blocks your current IP address, and will return an error if you try. Be careful when setting your first network policy.

## Step 4: submit your connection details

Provide the following details to complete the source setup:

1. The **name** is a descriptive name of the source
2. The **host** (e.g., `account.us-central1.gcp.snowflakecomputing.com`)
3. The **port** \[e.g., `443`]
4. The **database** from Step 2
5. The **username** from Step 2

## Terraform

If your organization manages infrastructure with Terraform, you can use the configuration below instead of the steps above. It sets up the same resources and permissions, using key-pair authentication.

* Use the official [`snowflakedb/snowflake`](https://registry.terraform.io/providers/snowflakedb/snowflake/latest/docs) provider, with `role = "ACCOUNTADMIN"` in your provider configuration. The objects it creates are owned by `ACCOUNTADMIN`, not `SYSADMIN` as in the setup script.
* In `terraform.tfvars`, set `public_key` (from Step 1), `database_name`, `schema_name`, and `warehouse_size`. The optional inputs and their defaults are `table_names` (empty, which grants access to all existing tables in the schema), `user_name` (`TRANSFER_USER`), `role_name` (`TRANSFER_ROLE`), `warehouse_name` (`TRANSFER_WAREHOUSE`), and `create_warehouse` (`true`).
* After `terraform apply`, use the `database` and `username` outputs, plus your host and port `443`, to complete the connection setup. Print each with `terraform output -raw <name>`.
* Names are converted to uppercase. If your account uses network policies, also complete the access policy step above. Views and tables created after `terraform apply` need their own grants.

```hcl title="main.tf" icon="code" expandable theme={null}
terraform {
  required_providers {
    snowflake = { source = "snowflakedb/snowflake" }
  }
}

variable "public_key" {
  type        = string
  description = "The public key provided to you."
}

variable "database_name" {
  type        = string
  description = "Existing database to read from. Converted to uppercase."
}

variable "schema_name" {
  type        = string
  description = "Existing schema to read from. Converted to uppercase."
}

variable "table_names" {
  type        = list(string)
  default     = []
  description = "Tables to grant SELECT on, converted to uppercase. Leave empty to grant SELECT on all tables that exist in the schema at apply time (not views or later tables)."
}

variable "user_name" {
  type    = string
  default = "TRANSFER_USER"
}

variable "role_name" {
  type    = string
  default = "TRANSFER_ROLE"
}

variable "warehouse_name" {
  type    = string
  default = "TRANSFER_WAREHOUSE"
}

variable "warehouse_size" {
  type        = string
  description = "Size of the new warehouse, e.g. XSMALL. Required, but only used when create_warehouse = true."
}

variable "create_warehouse" {
  type        = bool
  default     = true
  description = "When enabled, creates a new warehouse named warehouse_name. When disabled, uses an existing warehouse with that name."
}

locals {
  warehouse_name = upper(var.warehouse_name)
  database_name  = upper(var.database_name)
  schema_fqn     = "\"${upper(var.database_name)}\".\"${upper(var.schema_name)}\""
  # Accepts the key as it's been provided to you, with or without the PEM
  # header, footer, and line breaks.
  public_key = replace(replace(replace(replace(var.public_key,
  "-----BEGIN PUBLIC KEY-----", ""), "-----END PUBLIC KEY-----", ""), "\n", ""), "\r", "")
}

resource "snowflake_warehouse" "transfer" {
  count               = var.create_warehouse ? 1 : 0
  name                = local.warehouse_name
  warehouse_size      = var.warehouse_size
  warehouse_type      = "STANDARD"
  auto_suspend        = 60
  auto_resume         = true
  initially_suspended = true
}

resource "snowflake_account_role" "transfer" {
  name = upper(var.role_name)
}

resource "snowflake_grant_account_role" "to_sysadmin" {
  role_name        = snowflake_account_role.transfer.name
  parent_role_name = "SYSADMIN"
}

resource "snowflake_service_user" "transfer" {
  name              = upper(var.user_name)
  rsa_public_key    = local.public_key
  default_role      = snowflake_account_role.transfer.name
  default_warehouse = local.warehouse_name
}

resource "snowflake_grant_account_role" "to_user" {
  role_name = snowflake_account_role.transfer.name
  user_name = snowflake_service_user.transfer.name
}

resource "snowflake_grant_privileges_to_account_role" "warehouse" {
  account_role_name = snowflake_account_role.transfer.name
  privileges        = ["USAGE"]
  on_account_object {
    object_type = "WAREHOUSE"
    object_name = var.create_warehouse ? snowflake_warehouse.transfer[0].name : local.warehouse_name
  }
}

resource "snowflake_grant_privileges_to_account_role" "database" {
  account_role_name = snowflake_account_role.transfer.name
  privileges        = ["USAGE"]
  on_account_object {
    object_type = "DATABASE"
    object_name = local.database_name
  }
}

resource "snowflake_grant_privileges_to_account_role" "schema" {
  account_role_name = snowflake_account_role.transfer.name
  privileges        = ["USAGE"]
  on_schema {
    schema_name = local.schema_fqn
  }
}

resource "snowflake_grant_privileges_to_account_role" "tables" {
  for_each          = toset([for t in var.table_names : upper(t)])
  account_role_name = snowflake_account_role.transfer.name
  privileges        = ["SELECT"]
  on_schema_object {
    object_type = "TABLE"
    object_name = "${local.schema_fqn}.\"${each.value}\""
  }
}

resource "snowflake_grant_privileges_to_account_role" "all_tables" {
  count             = length(var.table_names) == 0 ? 1 : 0
  account_role_name = snowflake_account_role.transfer.name
  privileges        = ["SELECT"]
  on_schema_object {
    all {
      object_type_plural = "TABLES"
      in_schema          = local.schema_fqn
    }
  }
}

output "username" {
  value = snowflake_service_user.transfer.name
}

output "database" {
  value = local.database_name
}
```

```hcl title="terraform.tfvars" icon="code" expandable theme={null}
public_key     = <<-EOT
  -----BEGIN PUBLIC KEY-----
  MIIBIjANBgkqh...
  -----END PUBLIC KEY-----
EOT
database_name  = "MY_DATABASE"
schema_name    = "MY_SCHEMA"
warehouse_size = "XSMALL"
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.