diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 8cd50bcf02..a72ed7c95e 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -37,6 +37,13 @@ If you were not using this parameter, no changes are required. Related: [#4010](https://github.com/snowflakedb/terraform-provider-snowflake/issues/4010) +### *(new feature)* snowflake_listings datasource +Added a new preview data source for listings. See reference [docs](https://docs.snowflake.com/en/sql-reference/sql/show-listings). + +This data source focuses on base query commands (SHOW LISTINGS and DESCRIBE LISTING). Other query commands like SHOW AVAILABLE LISTINGS, DESCRIBE AVAILABLE LISTING, SHOW LISTING OFFERS, SHOW OFFERS, SHOW PRICING PLANS, and SHOW VERSIONS IN LISTING are not included and will be added depending on demand. + +This feature will be marked as a stable feature in future releases. Breaking changes are expected, even without bumping the major version. To use this feature, add `snowflake_listings_datasource` to `preview_features_enabled` field in the provider configuration. + ### *(improvement)* snowflake_scim_integration now accepts custom role names for run_as_role Previously, the `run_as_role` field in the [snowflake_scim_integration](https://registry.terraform.io/providers/snowflakedb/snowflake/2.11.0/docs/resources/scim_integration) resource only accepted predefined role names: `OKTA_PROVISIONER`, `AAD_PROVISIONER`, or `GENERIC_SCIM_PROVISIONER`. diff --git a/docs/data-sources/listings.md b/docs/data-sources/listings.md new file mode 100644 index 0000000000..36163aea63 --- /dev/null +++ b/docs/data-sources/listings.md @@ -0,0 +1,234 @@ +--- +page_title: "snowflake_listings Data Source - terraform-provider-snowflake" +subcategory: "Preview" +description: |- + Data source used to get details of filtered listings. Filtering is aligned with the current possibilities for SHOW LISTINGS query (like, starts_with, and limit are supported). The results of SHOW and DESCRIBE are encapsulated in one output collection. +--- + +!> **Preview Feature** This data source is a preview feature and is subject to breaking changes, even without bumping the major version. To use this feature, add `snowflake_listings_datasource` to `preview_features_enabled` field in the provider configuration. Read more about preview features in our [documentation](../#preview-features). + +-> **Note** This data source focuses on base query commands (SHOW LISTINGS and DESCRIBE LISTING). Other query commands like SHOW AVAILABLE LISTINGS, DESCRIBE AVAILABLE LISTING, SHOW LISTING OFFERS, SHOW OFFERS, SHOW PRICING PLANS, and SHOW VERSIONS IN LISTING are not included and will be added depending on demand. + +# snowflake_listings (Data Source) + +Data source used to get details of filtered listings. Filtering is aligned with the current possibilities for SHOW LISTINGS query (`like`, `starts_with`, and `limit` are supported). The results of SHOW and DESCRIBE are encapsulated in one output collection. + +## Example Usage + +```terraform +# Simple usage +data "snowflake_listings" "simple" { +} + +output "simple_output" { + value = data.snowflake_listings.simple.listings +} + +# Filtering (like) +data "snowflake_listings" "like" { + like = "listing-name" +} + +output "like_output" { + value = data.snowflake_listings.like.listings +} + +# Filtering by prefix (like) +data "snowflake_listings" "like_prefix" { + like = "prefix%" +} + +output "like_prefix_output" { + value = data.snowflake_listings.like_prefix.listings +} + +# Filtering (starts_with) +data "snowflake_listings" "starts_with" { + starts_with = "prefix-" +} + +output "starts_with_output" { + value = data.snowflake_listings.starts_with.listings +} + +# Filtering (limit) +data "snowflake_listings" "limit" { + limit { + rows = 10 + from = "prefix-" + } +} + +output "limit_output" { + value = data.snowflake_listings.limit.listings +} + +# Without additional data (to limit the number of calls make for every found listing) +data "snowflake_listings" "only_show" { + # with_describe is turned on by default and it calls DESCRIBE LISTING for every listing found and attaches its output to listings.*.describe_output field + with_describe = false +} + +output "only_show_output" { + value = data.snowflake_listings.only_show.listings +} + +# Ensure the number of listings is equal to at least one element (with the use of postcondition) +data "snowflake_listings" "assert_with_postcondition" { + like = "listing-name%" + lifecycle { + postcondition { + condition = length(self.listings) > 0 + error_message = "there should be at least one listing" + } + } +} + +# Ensure the number of listings is equal to exactly one element (with the use of check block) +check "listing_check" { + data "snowflake_listings" "assert_with_check_block" { + like = "listing-name" + } + + assert { + condition = length(data.snowflake_listings.assert_with_check_block.listings) == 1 + error_message = "listings filtered by '${data.snowflake_listings.assert_with_check_block.like}' returned ${length(data.snowflake_listings.assert_with_check_block.listings)} listings where one was expected" + } +} +``` + +-> **Note** If a field has a default value, it is shown next to the type in the schema. + + +## Schema + +### Optional + +- `like` (String) Filters the output with **case-insensitive** pattern, with support for SQL wildcard characters (`%` and `_`). +- `limit` (Block List, Max: 1) Limits the number of rows returned. If the `limit.from` is set, then the limit will start from the first element matched by the expression. The expression is only used to match with the first element, later on the elements are not matched by the prefix, but you can enforce a certain pattern with `starts_with` or `like`. (see [below for nested schema](#nestedblock--limit)) +- `starts_with` (String) Filters the output with **case-sensitive** characters indicating the beginning of the object name. +- `with_describe` (Boolean) (Default: `true`) Runs DESC LISTING for each listing returned by SHOW LISTINGS. The output of describe is saved to the description field. By default this value is set to true. + +### Read-Only + +- `id` (String) The ID of this resource. +- `listings` (List of Object) Holds the aggregated output of all listings details queries. (see [below for nested schema](#nestedatt--listings)) + + +### Nested Schema for `limit` + +Required: + +- `rows` (Number) The maximum number of rows to return. + +Optional: + +- `from` (String) Specifies a **case-sensitive** pattern that is used to match object name. After the first match, the limit on the number of rows will be applied. + + + +### Nested Schema for `listings` + +Read-Only: + +- `describe_output` (List of Object) (see [below for nested schema](#nestedobjatt--listings--describe_output)) +- `show_output` (List of Object) (see [below for nested schema](#nestedobjatt--listings--show_output)) + + +### Nested Schema for `listings.describe_output` + +Read-Only: + +- `application_package` (String) +- `approver_contact` (String) +- `business_needs` (String) +- `categories` (String) +- `comment` (String) +- `created_on` (String) +- `customized_contact_info` (String) +- `data_attributes` (String) +- `data_dictionary` (String) +- `data_preview` (String) +- `description` (String) +- `distribution` (String) +- `global_name` (String) +- `is_application` (Boolean) +- `is_by_request` (Boolean) +- `is_limited_trial` (Boolean) +- `is_monetized` (Boolean) +- `is_mountless_queryable` (Boolean) +- `is_share` (Boolean) +- `is_targeted` (Boolean) +- `last_committed_version_alias` (String) +- `last_committed_version_name` (String) +- `last_committed_version_uri` (String) +- `legacy_uniform_listing_locators` (String) +- `limited_trial_plan` (String) +- `listing_terms` (String) +- `live_version_uri` (String) +- `manifest_yaml` (String) +- `monetization_display_order` (String) +- `name` (String) +- `organization_profile_name` (String) +- `owner` (String) +- `owner_role_type` (String) +- `profile` (String) +- `published_on` (String) +- `published_version_alias` (String) +- `published_version_name` (String) +- `published_version_uri` (String) +- `refresh_schedule` (String) +- `refresh_type` (String) +- `regions` (String) +- `rejection_reason` (String) +- `request_approval_type` (String) +- `resources` (String) +- `retried_on` (String) +- `review_state` (String) +- `revisions` (String) +- `scheduled_drop_time` (String) +- `share` (String) +- `state` (String) +- `subtitle` (String) +- `support_contact` (String) +- `target_accounts` (String) +- `title` (String) +- `trial_details` (String) +- `uniform_listing_locator` (String) +- `unpublished_by_admin_reasons` (String) +- `updated_on` (String) +- `usage_examples` (String) + + + +### Nested Schema for `listings.show_output` + +Read-Only: + +- `comment` (String) +- `created_on` (String) +- `detailed_target_accounts` (String) +- `distribution` (String) +- `global_name` (String) +- `is_application` (Boolean) +- `is_by_request` (Boolean) +- `is_limited_trial` (Boolean) +- `is_monetized` (Boolean) +- `is_mountless_queryable` (Boolean) +- `is_targeted` (Boolean) +- `name` (String) +- `organization_profile_name` (String) +- `owner` (String) +- `owner_role_type` (String) +- `profile` (String) +- `published_on` (String) +- `regions` (String) +- `rejected_on` (String) +- `review_state` (String) +- `state` (String) +- `subtitle` (String) +- `target_accounts` (String) +- `title` (String) +- `uniform_listing_locator` (String) +- `updated_on` (String) + diff --git a/docs/index.md b/docs/index.md index 608f2ad70c..aba08988bc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -142,7 +142,7 @@ provider "snowflake" { - `passcode_in_password` (Boolean) False by default. Set to true if the MFA passcode is embedded to the configured password. Can also be sourced from the `SNOWFLAKE_PASSCODE_IN_PASSWORD` environment variable. - `password` (String, Sensitive) Password for user + password or [token](https://docs.snowflake.com/en/user-guide/programmatic-access-tokens#generating-a-programmatic-access-token) for [PAT auth](https://docs.snowflake.com/en/user-guide/programmatic-access-tokens). Cannot be used with `private_key` and `private_key_passphrase`. Can also be sourced from the `SNOWFLAKE_PASSWORD` environment variable. - `port` (Number) Specifies a custom port value used by the driver for privatelink connections. Can also be sourced from the `SNOWFLAKE_PORT` environment variable. -- `preview_features_enabled` (Set of String) A list of preview features that are handled by the provider. See [preview features list](https://github.com/Snowflake-Labs/terraform-provider-snowflake/blob/main/v1-preparations/LIST_OF_PREVIEW_FEATURES_FOR_V1.md). Preview features may have breaking changes in future releases, even without raising the major version. This field can not be set with environmental variables. Preview features that can be enabled are: `snowflake_account_authentication_policy_attachment_resource` | `snowflake_account_password_policy_attachment_resource` | `snowflake_alert_resource` | `snowflake_alerts_datasource` | `snowflake_api_integration_resource` | `snowflake_authentication_policy_resource` | `snowflake_authentication_policies_datasource` | `snowflake_cortex_search_service_resource` | `snowflake_cortex_search_services_datasource` | `snowflake_current_account_resource` | `snowflake_current_account_datasource` | `snowflake_current_organization_account_resource` | `snowflake_database_datasource` | `snowflake_database_role_datasource` | `snowflake_dynamic_table_resource` | `snowflake_dynamic_tables_datasource` | `snowflake_external_function_resource` | `snowflake_external_functions_datasource` | `snowflake_external_table_resource` | `snowflake_external_tables_datasource` | `snowflake_external_volume_resource` | `snowflake_failover_group_resource` | `snowflake_failover_groups_datasource` | `snowflake_file_format_resource` | `snowflake_file_formats_datasource` | `snowflake_function_java_resource` | `snowflake_function_javascript_resource` | `snowflake_function_python_resource` | `snowflake_function_scala_resource` | `snowflake_function_sql_resource` | `snowflake_functions_datasource` | `snowflake_job_service_resource` | `snowflake_managed_account_resource` | `snowflake_materialized_view_resource` | `snowflake_materialized_views_datasource` | `snowflake_network_policy_attachment_resource` | `snowflake_network_rule_resource` | `snowflake_notebook_resource` | `snowflake_notebooks_datasource` | `snowflake_email_notification_integration_resource` | `snowflake_notification_integration_resource` | `snowflake_object_parameter_resource` | `snowflake_password_policy_resource` | `snowflake_pipe_resource` | `snowflake_pipes_datasource` | `snowflake_current_role_datasource` | `snowflake_semantic_view_resource` | `snowflake_semantic_views_datasource` | `snowflake_sequence_resource` | `snowflake_sequences_datasource` | `snowflake_share_resource` | `snowflake_shares_datasource` | `snowflake_parameters_datasource` | `snowflake_procedure_java_resource` | `snowflake_procedure_javascript_resource` | `snowflake_procedure_python_resource` | `snowflake_procedure_scala_resource` | `snowflake_procedure_sql_resource` | `snowflake_procedures_datasource` | `snowflake_stage_resource` | `snowflake_stages_datasource` | `snowflake_storage_integration_resource` | `snowflake_storage_integrations_datasource` | `snowflake_system_generate_scim_access_token_datasource` | `snowflake_system_get_aws_sns_iam_policy_datasource` | `snowflake_system_get_privatelink_config_datasource` | `snowflake_system_get_snowflake_platform_info_datasource` | `snowflake_table_column_masking_policy_application_resource` | `snowflake_table_constraint_resource` | `snowflake_table_resource` | `snowflake_tables_datasource` | `snowflake_user_authentication_policy_attachment_resource` | `snowflake_user_public_keys_resource` | `snowflake_user_password_policy_attachment_resource`. Promoted features that are stable and are enabled by default are: `snowflake_compute_pool_resource` | `snowflake_compute_pools_datasource` | `snowflake_git_repository_resource` | `snowflake_git_repositories_datasource` | `snowflake_image_repository_resource` | `snowflake_image_repositories_datasource` | `snowflake_listing_resource` | `snowflake_service_resource` | `snowflake_services_datasource` | `snowflake_user_programmatic_access_token_resource` | `snowflake_user_programmatic_access_tokens_datasource`. Promoted features can be safely removed from this field. They will be removed in the next major version. +- `preview_features_enabled` (Set of String) A list of preview features that are handled by the provider. See [preview features list](https://github.com/Snowflake-Labs/terraform-provider-snowflake/blob/main/v1-preparations/LIST_OF_PREVIEW_FEATURES_FOR_V1.md). Preview features may have breaking changes in future releases, even without raising the major version. This field can not be set with environmental variables. Preview features that can be enabled are: `snowflake_account_authentication_policy_attachment_resource` | `snowflake_account_password_policy_attachment_resource` | `snowflake_alert_resource` | `snowflake_alerts_datasource` | `snowflake_api_integration_resource` | `snowflake_authentication_policy_resource` | `snowflake_authentication_policies_datasource` | `snowflake_cortex_search_service_resource` | `snowflake_cortex_search_services_datasource` | `snowflake_current_account_resource` | `snowflake_current_account_datasource` | `snowflake_current_organization_account_resource` | `snowflake_database_datasource` | `snowflake_database_role_datasource` | `snowflake_dynamic_table_resource` | `snowflake_dynamic_tables_datasource` | `snowflake_external_function_resource` | `snowflake_external_functions_datasource` | `snowflake_external_table_resource` | `snowflake_external_tables_datasource` | `snowflake_external_volume_resource` | `snowflake_failover_group_resource` | `snowflake_failover_groups_datasource` | `snowflake_file_format_resource` | `snowflake_file_formats_datasource` | `snowflake_function_java_resource` | `snowflake_function_javascript_resource` | `snowflake_function_python_resource` | `snowflake_function_scala_resource` | `snowflake_function_sql_resource` | `snowflake_functions_datasource` | `snowflake_job_service_resource` | `snowflake_listings_datasource` | `snowflake_managed_account_resource` | `snowflake_materialized_view_resource` | `snowflake_materialized_views_datasource` | `snowflake_network_policy_attachment_resource` | `snowflake_network_rule_resource` | `snowflake_notebook_resource` | `snowflake_notebooks_datasource` | `snowflake_email_notification_integration_resource` | `snowflake_notification_integration_resource` | `snowflake_object_parameter_resource` | `snowflake_password_policy_resource` | `snowflake_pipe_resource` | `snowflake_pipes_datasource` | `snowflake_current_role_datasource` | `snowflake_semantic_view_resource` | `snowflake_semantic_views_datasource` | `snowflake_sequence_resource` | `snowflake_sequences_datasource` | `snowflake_share_resource` | `snowflake_shares_datasource` | `snowflake_parameters_datasource` | `snowflake_procedure_java_resource` | `snowflake_procedure_javascript_resource` | `snowflake_procedure_python_resource` | `snowflake_procedure_scala_resource` | `snowflake_procedure_sql_resource` | `snowflake_procedures_datasource` | `snowflake_stage_resource` | `snowflake_stages_datasource` | `snowflake_storage_integration_resource` | `snowflake_storage_integrations_datasource` | `snowflake_system_generate_scim_access_token_datasource` | `snowflake_system_get_aws_sns_iam_policy_datasource` | `snowflake_system_get_privatelink_config_datasource` | `snowflake_system_get_snowflake_platform_info_datasource` | `snowflake_table_column_masking_policy_application_resource` | `snowflake_table_constraint_resource` | `snowflake_table_resource` | `snowflake_tables_datasource` | `snowflake_user_authentication_policy_attachment_resource` | `snowflake_user_public_keys_resource` | `snowflake_user_password_policy_attachment_resource`. Promoted features that are stable and are enabled by default are: `snowflake_compute_pool_resource` | `snowflake_compute_pools_datasource` | `snowflake_git_repository_resource` | `snowflake_git_repositories_datasource` | `snowflake_image_repository_resource` | `snowflake_image_repositories_datasource` | `snowflake_listing_resource` | `snowflake_service_resource` | `snowflake_services_datasource` | `snowflake_user_programmatic_access_token_resource` | `snowflake_user_programmatic_access_tokens_datasource`. Promoted features can be safely removed from this field. They will be removed in the next major version. - `private_key` (String, Sensitive) Private Key for username+private-key auth. Cannot be used with `password`. Can also be sourced from the `SNOWFLAKE_PRIVATE_KEY` environment variable. - `private_key_passphrase` (String, Sensitive) Supports the encryption ciphers aes-128-cbc, aes-128-gcm, aes-192-cbc, aes-192-gcm, aes-256-cbc, aes-256-gcm, and des-ede3-cbc. Can also be sourced from the `SNOWFLAKE_PRIVATE_KEY_PASSPHRASE` environment variable. - `profile` (String) Sets the profile to read from ~/.snowflake/config file. Can also be sourced from the `SNOWFLAKE_PROFILE` environment variable. @@ -790,6 +790,7 @@ To use them, add the relevant feature name to the `preview_features_enabled` fie - [snowflake_failover_groups](./docs/data-sources/failover_groups) - [snowflake_file_formats](./docs/data-sources/file_formats) - [snowflake_functions](./docs/data-sources/functions) +- [snowflake_listings](./docs/data-sources/listings) - [snowflake_materialized_views](./docs/data-sources/materialized_views) - [snowflake_notebooks](./docs/data-sources/notebooks) - [snowflake_parameters](./docs/data-sources/parameters) diff --git a/examples/additional/preview_data_sources.MD b/examples/additional/preview_data_sources.MD index 3f286820c0..b82da14f98 100644 --- a/examples/additional/preview_data_sources.MD +++ b/examples/additional/preview_data_sources.MD @@ -14,6 +14,7 @@ - [snowflake_failover_groups](./docs/data-sources/failover_groups) - [snowflake_file_formats](./docs/data-sources/file_formats) - [snowflake_functions](./docs/data-sources/functions) +- [snowflake_listings](./docs/data-sources/listings) - [snowflake_materialized_views](./docs/data-sources/materialized_views) - [snowflake_notebooks](./docs/data-sources/notebooks) - [snowflake_parameters](./docs/data-sources/parameters) diff --git a/examples/data-sources/snowflake_listings/data-source.tf b/examples/data-sources/snowflake_listings/data-source.tf new file mode 100644 index 0000000000..05374639d4 --- /dev/null +++ b/examples/data-sources/snowflake_listings/data-source.tf @@ -0,0 +1,80 @@ +# Simple usage +data "snowflake_listings" "simple" { +} + +output "simple_output" { + value = data.snowflake_listings.simple.listings +} + +# Filtering (like) +data "snowflake_listings" "like" { + like = "listing-name" +} + +output "like_output" { + value = data.snowflake_listings.like.listings +} + +# Filtering by prefix (like) +data "snowflake_listings" "like_prefix" { + like = "prefix%" +} + +output "like_prefix_output" { + value = data.snowflake_listings.like_prefix.listings +} + +# Filtering (starts_with) +data "snowflake_listings" "starts_with" { + starts_with = "prefix-" +} + +output "starts_with_output" { + value = data.snowflake_listings.starts_with.listings +} + +# Filtering (limit) +data "snowflake_listings" "limit" { + limit { + rows = 10 + from = "prefix-" + } +} + +output "limit_output" { + value = data.snowflake_listings.limit.listings +} + +# Without additional data (to limit the number of calls make for every found listing) +data "snowflake_listings" "only_show" { + # with_describe is turned on by default and it calls DESCRIBE LISTING for every listing found and attaches its output to listings.*.describe_output field + with_describe = false +} + +output "only_show_output" { + value = data.snowflake_listings.only_show.listings +} + +# Ensure the number of listings is equal to at least one element (with the use of postcondition) +data "snowflake_listings" "assert_with_postcondition" { + like = "listing-name%" + lifecycle { + postcondition { + condition = length(self.listings) > 0 + error_message = "there should be at least one listing" + } + } +} + +# Ensure the number of listings is equal to exactly one element (with the use of check block) +check "listing_check" { + data "snowflake_listings" "assert_with_check_block" { + like = "listing-name" + } + + assert { + condition = length(data.snowflake_listings.assert_with_check_block.listings) == 1 + error_message = "listings filtered by '${data.snowflake_listings.assert_with_check_block.like}' returned ${length(data.snowflake_listings.assert_with_check_block.listings)} listings where one was expected" + } +} + diff --git a/pkg/acceptance/bettertestspoc/assert/resourceshowoutputassert/listings_datasource_show_output_ext.go b/pkg/acceptance/bettertestspoc/assert/resourceshowoutputassert/listings_datasource_show_output_ext.go new file mode 100644 index 0000000000..50cb83c2e0 --- /dev/null +++ b/pkg/acceptance/bettertestspoc/assert/resourceshowoutputassert/listings_datasource_show_output_ext.go @@ -0,0 +1,18 @@ +package resourceshowoutputassert + +import ( + "testing" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert" +) + +// ListingsDatasourceShowOutput is a temporary workaround to have better show output assertions in data source acceptance tests. +func ListingsDatasourceShowOutput(t *testing.T, datasourceReference string) *ListingShowOutputAssert { + t.Helper() + + l := ListingShowOutputAssert{ + ResourceAssert: assert.NewDatasourceAssert(datasourceReference, "show_output", "listings.0."), + } + l.AddAssertion(assert.ValueSet("show_output.#", "1")) + return &l +} diff --git a/pkg/acceptance/bettertestspoc/config/datasourcemodel/gen/datasource_schema_def.go b/pkg/acceptance/bettertestspoc/config/datasourcemodel/gen/datasource_schema_def.go index ad35412001..261618b1b0 100644 --- a/pkg/acceptance/bettertestspoc/config/datasourcemodel/gen/datasource_schema_def.go +++ b/pkg/acceptance/bettertestspoc/config/datasourcemodel/gen/datasource_schema_def.go @@ -70,6 +70,10 @@ var allDatasourcesSchemaDefs = []DatasourceSchemaDef{ name: "ImageRepositories", schema: datasources.ImageRepositories().Schema, }, + { + name: "Listings", + schema: datasources.Listings().Schema, + }, { name: "MaskingPolicies", schema: datasources.MaskingPolicies().Schema, diff --git a/pkg/acceptance/bettertestspoc/config/datasourcemodel/listings_model_ext.go b/pkg/acceptance/bettertestspoc/config/datasourcemodel/listings_model_ext.go new file mode 100644 index 0000000000..2168b11959 --- /dev/null +++ b/pkg/acceptance/bettertestspoc/config/datasourcemodel/listings_model_ext.go @@ -0,0 +1,22 @@ +package datasourcemodel + +import ( + tfconfig "github.com/hashicorp/terraform-plugin-testing/config" +) + +func (l *ListingsModel) WithLimit(rows int) *ListingsModel { + return l.WithLimitValue( + tfconfig.ObjectVariable(map[string]tfconfig.Variable{ + "rows": tfconfig.IntegerVariable(rows), + }), + ) +} + +func (l *ListingsModel) WithRowsAndFrom(rows int, from string) *ListingsModel { + return l.WithLimitValue( + tfconfig.ObjectVariable(map[string]tfconfig.Variable{ + "rows": tfconfig.IntegerVariable(rows), + "from": tfconfig.StringVariable(from), + }), + ) +} diff --git a/pkg/acceptance/bettertestspoc/config/datasourcemodel/listings_model_gen.go b/pkg/acceptance/bettertestspoc/config/datasourcemodel/listings_model_gen.go new file mode 100644 index 0000000000..8b754b9ffd --- /dev/null +++ b/pkg/acceptance/bettertestspoc/config/datasourcemodel/listings_model_gen.go @@ -0,0 +1,111 @@ +// Code generated by data source model builder generator (v0.1.0); DO NOT EDIT. + +package datasourcemodel + +import ( + "encoding/json" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/config" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/datasources" + tfconfig "github.com/hashicorp/terraform-plugin-testing/config" +) + +type ListingsModel struct { + Like tfconfig.Variable `json:"like,omitempty"` + Limit tfconfig.Variable `json:"limit,omitempty"` + Listings tfconfig.Variable `json:"listings,omitempty"` + StartsWith tfconfig.Variable `json:"starts_with,omitempty"` + WithDescribe tfconfig.Variable `json:"with_describe,omitempty"` + + *config.DatasourceModelMeta +} + +///////////////////////////////////////////////// +// Basic builders (resource name and required) // +///////////////////////////////////////////////// + +func Listings( + datasourceName string, +) *ListingsModel { + l := &ListingsModel{DatasourceModelMeta: config.DatasourceMeta(datasourceName, datasources.Listings)} + return l +} + +func ListingsWithDefaultMeta() *ListingsModel { + l := &ListingsModel{DatasourceModelMeta: config.DatasourceDefaultMeta(datasources.Listings)} + return l +} + +/////////////////////////////////////////////////////// +// set proper json marshalling and handle depends on // +/////////////////////////////////////////////////////// + +func (l *ListingsModel) MarshalJSON() ([]byte, error) { + type Alias ListingsModel + return json.Marshal(&struct { + *Alias + DependsOn []string `json:"depends_on,omitempty"` + SingleAttributeWorkaround config.ReplacementPlaceholder `json:"single_attribute_workaround,omitempty"` + }{ + Alias: (*Alias)(l), + DependsOn: l.DependsOn(), + SingleAttributeWorkaround: config.SnowflakeProviderConfigSingleAttributeWorkaround, + }) +} + +func (l *ListingsModel) WithDependsOn(values ...string) *ListingsModel { + l.SetDependsOn(values...) + return l +} + +///////////////////////////////// +// below all the proper values // +///////////////////////////////// + +func (l *ListingsModel) WithLike(like string) *ListingsModel { + l.Like = tfconfig.StringVariable(like) + return l +} + +// limit attribute type is not yet supported, so WithLimit can't be generated + +// listings attribute type is not yet supported, so WithListings can't be generated + +func (l *ListingsModel) WithStartsWith(startsWith string) *ListingsModel { + l.StartsWith = tfconfig.StringVariable(startsWith) + return l +} + +func (l *ListingsModel) WithWithDescribe(withDescribe bool) *ListingsModel { + l.WithDescribe = tfconfig.BoolVariable(withDescribe) + return l +} + +////////////////////////////////////////// +// below it's possible to set any value // +////////////////////////////////////////// + +func (l *ListingsModel) WithLikeValue(value tfconfig.Variable) *ListingsModel { + l.Like = value + return l +} + +func (l *ListingsModel) WithLimitValue(value tfconfig.Variable) *ListingsModel { + l.Limit = value + return l +} + +func (l *ListingsModel) WithListingsValue(value tfconfig.Variable) *ListingsModel { + l.Listings = value + return l +} + +func (l *ListingsModel) WithStartsWithValue(value tfconfig.Variable) *ListingsModel { + l.StartsWith = value + return l +} + +func (l *ListingsModel) WithWithDescribeValue(value tfconfig.Variable) *ListingsModel { + l.WithDescribe = value + return l +} diff --git a/pkg/datasources/listings.go b/pkg/datasources/listings.go new file mode 100644 index 0000000000..f8673b9a17 --- /dev/null +++ b/pkg/datasources/listings.go @@ -0,0 +1,91 @@ +package datasources + +import ( + "context" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/datasources" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/previewfeatures" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/resources" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/schemas" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +var listingsSchema = map[string]*schema.Schema{ + "with_describe": { + Type: schema.TypeBool, + Optional: true, + Default: true, + Description: "Runs DESC LISTING for each listing returned by SHOW LISTINGS. The output of describe is saved to the description field. By default this value is set to true.", + }, + "like": likeSchema, + "starts_with": startsWithSchema, + "limit": limitFromSchema, + "listings": { + Type: schema.TypeList, + Computed: true, + Description: "Holds the aggregated output of all listings details queries.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + resources.ShowOutputAttributeName: { + Type: schema.TypeList, + Computed: true, + Description: "Holds the output of SHOW LISTINGS.", + Elem: &schema.Resource{Schema: schemas.ShowListingSchema}, + }, + resources.DescribeOutputAttributeName: { + Type: schema.TypeList, + Computed: true, + Description: "Holds the output of DESCRIBE LISTING.", + Elem: &schema.Resource{Schema: schemas.DescribeListingSchema}, + }, + }, + }, + }, +} + +func Listings() *schema.Resource { + return &schema.Resource{ + ReadContext: PreviewFeatureReadWrapper(string(previewfeatures.ListingsDatasource), TrackingReadWrapper(datasources.Listings, ReadListings)), + Schema: listingsSchema, + Description: "Data source used to get details of filtered listings. Filtering is aligned with the current possibilities for SHOW LISTINGS query (`like`, `starts_with`, and `limit` are supported). The results of SHOW and DESCRIBE are encapsulated in one output collection.", + } +} + +func ReadListings(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics { + client := meta.(*provider.Context).Client + req := new(sdk.ShowListingRequest) + + handleLike(d, &req.Like) + handleStartsWith(d, &req.StartsWith) + handleLimitFrom(d, &req.Limit) + + listings, err := client.Listings.Show(ctx, req) + if err != nil { + return diag.FromErr(err) + } + d.SetId("listings_read") + + flattened := make([]map[string]any, len(listings)) + for i, listing := range listings { + listing := listing + var describe []map[string]any + if d.Get("with_describe").(bool) { + details, err := client.Listings.Describe(ctx, sdk.NewDescribeListingRequest(listing.ID())) + if err != nil { + return diag.FromErr(err) + } + describe = []map[string]any{schemas.ListingDetailsToSchema(details)} + } + flattened[i] = map[string]any{ + resources.ShowOutputAttributeName: []map[string]any{schemas.ListingToSchema(&listing)}, + resources.DescribeOutputAttributeName: describe, + } + } + if err := d.Set("listings", flattened); err != nil { + return diag.FromErr(err) + } + return nil +} diff --git a/pkg/provider/datasources/datasources.go b/pkg/provider/datasources/datasources.go index af3e3bb903..2cf9776c4f 100644 --- a/pkg/provider/datasources/datasources.go +++ b/pkg/provider/datasources/datasources.go @@ -25,6 +25,7 @@ const ( GitRepositories datasource = "snowflake_git_repositories" Grants datasource = "snowflake_grants" ImageRepositories datasource = "snowflake_image_repositories" + Listings datasource = "snowflake_listings" MaskingPolicies datasource = "snowflake_masking_policies" MaterializedViews datasource = "snowflake_materialized_views" NetworkPolicies datasource = "snowflake_network_policies" diff --git a/pkg/provider/previewfeatures/preview_features.go b/pkg/provider/previewfeatures/preview_features.go index 33c2d95d23..f490380e48 100644 --- a/pkg/provider/previewfeatures/preview_features.go +++ b/pkg/provider/previewfeatures/preview_features.go @@ -51,6 +51,7 @@ const ( ImageRepositoriesDatasource feature = "snowflake_image_repositories_datasource" JobServiceResource feature = "snowflake_job_service_resource" ListingResource feature = "snowflake_listing_resource" + ListingsDatasource feature = "snowflake_listings_datasource" ManagedAccountResource feature = "snowflake_managed_account_resource" MaterializedViewResource feature = "snowflake_materialized_view_resource" MaterializedViewsDatasource feature = "snowflake_materialized_views_datasource" @@ -131,6 +132,7 @@ var allPreviewFeatures = []feature{ FunctionSqlResource, FunctionsDatasource, JobServiceResource, + ListingsDatasource, ManagedAccountResource, MaterializedViewResource, MaterializedViewsDatasource, diff --git a/pkg/provider/previewfeatures/preview_features_test.go b/pkg/provider/previewfeatures/preview_features_test.go index c9cc170cf2..013c35b156 100644 --- a/pkg/provider/previewfeatures/preview_features_test.go +++ b/pkg/provider/previewfeatures/preview_features_test.go @@ -50,6 +50,7 @@ func Test_StringToFeature(t *testing.T) { {input: "snowflake_image_repositories_datasource", want: ImageRepositoriesDatasource}, {input: "snowflake_job_service_resource", want: JobServiceResource}, {input: "snowflake_listing_resource", want: ListingResource}, + {input: "snowflake_listings_datasource", want: ListingsDatasource}, {input: "snowflake_managed_account_resource", want: ManagedAccountResource}, {input: "snowflake_materialized_view_resource", want: MaterializedViewResource}, {input: "snowflake_materialized_views_datasource", want: MaterializedViewsDatasource}, diff --git a/pkg/provider/provider.go b/pkg/provider/provider.go index 6095aa3f97..b96db1980a 100644 --- a/pkg/provider/provider.go +++ b/pkg/provider/provider.go @@ -620,6 +620,7 @@ func getDataSources() map[string]*schema.Resource { "snowflake_git_repositories": datasources.GitRepositories(), "snowflake_grants": datasources.Grants(), "snowflake_image_repositories": datasources.ImageRepositories(), + "snowflake_listings": datasources.Listings(), "snowflake_masking_policies": datasources.MaskingPolicies(), "snowflake_materialized_views": datasources.MaterializedViews(), "snowflake_network_policies": datasources.NetworkPolicies(), diff --git a/pkg/schemas/listing_details.go b/pkg/schemas/listing_details.go new file mode 100644 index 0000000000..d8d9f4717c --- /dev/null +++ b/pkg/schemas/listing_details.go @@ -0,0 +1,225 @@ +package schemas + +import ( + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// DescribeListingSchema represents output of DESCRIBE LISTING for a single Listing. +var DescribeListingSchema = map[string]*schema.Schema{ + "global_name": {Type: schema.TypeString, Computed: true}, + "name": {Type: schema.TypeString, Computed: true}, + "owner": {Type: schema.TypeString, Computed: true}, + "owner_role_type": {Type: schema.TypeString, Computed: true}, + "created_on": {Type: schema.TypeString, Computed: true}, + "updated_on": {Type: schema.TypeString, Computed: true}, + "published_on": {Type: schema.TypeString, Computed: true}, + "title": {Type: schema.TypeString, Computed: true}, + "subtitle": {Type: schema.TypeString, Computed: true}, + "description": {Type: schema.TypeString, Computed: true}, + "listing_terms": {Type: schema.TypeString, Computed: true}, + "state": {Type: schema.TypeString, Computed: true}, + "share": {Type: schema.TypeString, Computed: true}, + "application_package": {Type: schema.TypeString, Computed: true}, + "business_needs": {Type: schema.TypeString, Computed: true}, + "usage_examples": {Type: schema.TypeString, Computed: true}, + "data_attributes": {Type: schema.TypeString, Computed: true}, + "categories": {Type: schema.TypeString, Computed: true}, + "resources": {Type: schema.TypeString, Computed: true}, + "profile": {Type: schema.TypeString, Computed: true}, + "customized_contact_info": {Type: schema.TypeString, Computed: true}, + "data_dictionary": {Type: schema.TypeString, Computed: true}, + "data_preview": {Type: schema.TypeString, Computed: true}, + "comment": {Type: schema.TypeString, Computed: true}, + "revisions": {Type: schema.TypeString, Computed: true}, + "target_accounts": {Type: schema.TypeString, Computed: true}, + "regions": {Type: schema.TypeString, Computed: true}, + "refresh_schedule": {Type: schema.TypeString, Computed: true}, + "refresh_type": {Type: schema.TypeString, Computed: true}, + "review_state": {Type: schema.TypeString, Computed: true}, + "rejection_reason": {Type: schema.TypeString, Computed: true}, + "unpublished_by_admin_reasons": {Type: schema.TypeString, Computed: true}, + "is_monetized": {Type: schema.TypeBool, Computed: true}, + "is_application": {Type: schema.TypeBool, Computed: true}, + "is_targeted": {Type: schema.TypeBool, Computed: true}, + "is_limited_trial": {Type: schema.TypeBool, Computed: true}, + "is_by_request": {Type: schema.TypeBool, Computed: true}, + "limited_trial_plan": {Type: schema.TypeString, Computed: true}, + "retried_on": {Type: schema.TypeString, Computed: true}, + "scheduled_drop_time": {Type: schema.TypeString, Computed: true}, + "manifest_yaml": {Type: schema.TypeString, Computed: true}, + "distribution": {Type: schema.TypeString, Computed: true}, + "is_mountless_queryable": {Type: schema.TypeBool, Computed: true}, + "organization_profile_name": {Type: schema.TypeString, Computed: true}, + "uniform_listing_locator": {Type: schema.TypeString, Computed: true}, + "trial_details": {Type: schema.TypeString, Computed: true}, + "approver_contact": {Type: schema.TypeString, Computed: true}, + "support_contact": {Type: schema.TypeString, Computed: true}, + "live_version_uri": {Type: schema.TypeString, Computed: true}, + "last_committed_version_uri": {Type: schema.TypeString, Computed: true}, + "last_committed_version_name": {Type: schema.TypeString, Computed: true}, + "last_committed_version_alias": {Type: schema.TypeString, Computed: true}, + "published_version_uri": {Type: schema.TypeString, Computed: true}, + "published_version_name": {Type: schema.TypeString, Computed: true}, + "published_version_alias": {Type: schema.TypeString, Computed: true}, + "is_share": {Type: schema.TypeBool, Computed: true}, + "request_approval_type": {Type: schema.TypeString, Computed: true}, + "monetization_display_order": {Type: schema.TypeString, Computed: true}, + "legacy_uniform_listing_locators": {Type: schema.TypeString, Computed: true}, +} + +func ListingDetailsToSchema(details *sdk.ListingDetails) map[string]any { + m := make(map[string]any) + m["global_name"] = details.GlobalName + m["name"] = details.Name + m["owner"] = details.Owner + m["owner_role_type"] = details.OwnerRoleType + m["created_on"] = details.CreatedOn + m["updated_on"] = details.UpdatedOn + if details.PublishedOn != nil { + m["published_on"] = details.PublishedOn + } + m["title"] = details.Title + if details.Subtitle != nil { + m["subtitle"] = details.Subtitle + } + if details.Description != nil { + m["description"] = details.Description + } + if details.ListingTerms != nil { + m["listing_terms"] = details.ListingTerms + } + m["state"] = string(details.State) + if details.Share != nil { + m["share"] = details.Share.Name() + } + if details.ApplicationPackage != nil { + m["application_package"] = details.ApplicationPackage.Name() + } + if details.BusinessNeeds != nil { + m["business_needs"] = details.BusinessNeeds + } + if details.UsageExamples != nil { + m["usage_examples"] = details.UsageExamples + } + if details.DataAttributes != nil { + m["data_attributes"] = details.DataAttributes + } + if details.Categories != nil { + m["categories"] = details.Categories + } + if details.Resources != nil { + m["resources"] = details.Resources + } + if details.Profile != nil { + m["profile"] = details.Profile + } + if details.CustomizedContactInfo != nil { + m["customized_contact_info"] = details.CustomizedContactInfo + } + if details.DataDictionary != nil { + m["data_dictionary"] = details.DataDictionary + } + if details.DataPreview != nil { + m["data_preview"] = details.DataPreview + } + if details.Comment != nil { + m["comment"] = details.Comment + } + m["revisions"] = details.Revisions + if details.TargetAccounts != nil { + m["target_accounts"] = details.TargetAccounts + } + if details.Regions != nil { + m["regions"] = details.Regions + } + if details.RefreshSchedule != nil { + m["refresh_schedule"] = details.RefreshSchedule + } + if details.RefreshType != nil { + m["refresh_type"] = details.RefreshType + } + if details.ReviewState != nil { + m["review_state"] = details.ReviewState + } + if details.RejectionReason != nil { + m["rejection_reason"] = details.RejectionReason + } + if details.UnpublishedByAdminReasons != nil { + m["unpublished_by_admin_reasons"] = details.UnpublishedByAdminReasons + } + m["is_monetized"] = details.IsMonetized + m["is_application"] = details.IsApplication + m["is_targeted"] = details.IsTargeted + if details.IsLimitedTrial != nil { + m["is_limited_trial"] = details.IsLimitedTrial + } + if details.IsByRequest != nil { + m["is_by_request"] = details.IsByRequest + } + if details.LimitedTrialPlan != nil { + m["limited_trial_plan"] = details.LimitedTrialPlan + } + if details.RetriedOn != nil { + m["retried_on"] = details.RetriedOn + } + if details.ScheduledDropTime != nil { + m["scheduled_drop_time"] = details.ScheduledDropTime + } + m["manifest_yaml"] = details.ManifestYaml + if details.Distribution != nil { + m["distribution"] = details.Distribution + } + if details.IsMountlessQueryable != nil { + m["is_mountless_queryable"] = details.IsMountlessQueryable + } + if details.OrganizationProfileName != nil { + m["organization_profile_name"] = details.OrganizationProfileName + } + if details.UniformListingLocator != nil { + m["uniform_listing_locator"] = details.UniformListingLocator + } + if details.TrialDetails != nil { + m["trial_details"] = details.TrialDetails + } + if details.ApproverContact != nil { + m["approver_contact"] = details.ApproverContact + } + if details.SupportContact != nil { + m["support_contact"] = details.SupportContact + } + if details.LiveVersionUri != nil { + m["live_version_uri"] = details.LiveVersionUri + } + if details.LastCommittedVersionUri != nil { + m["last_committed_version_uri"] = details.LastCommittedVersionUri + } + if details.LastCommittedVersionName != nil { + m["last_committed_version_name"] = details.LastCommittedVersionName + } + if details.LastCommittedVersionAlias != nil { + m["last_committed_version_alias"] = details.LastCommittedVersionAlias + } + if details.PublishedVersionUri != nil { + m["published_version_uri"] = details.PublishedVersionUri + } + if details.PublishedVersionName != nil { + m["published_version_name"] = details.PublishedVersionName + } + if details.PublishedVersionAlias != nil { + m["published_version_alias"] = details.PublishedVersionAlias + } + if details.IsShare != nil { + m["is_share"] = details.IsShare + } + if details.RequestApprovalType != nil { + m["request_approval_type"] = details.RequestApprovalType + } + if details.MonetizationDisplayOrder != nil { + m["monetization_display_order"] = details.MonetizationDisplayOrder + } + if details.LegacyUniformListingLocators != nil { + m["legacy_uniform_listing_locators"] = details.LegacyUniformListingLocators + } + return m +} diff --git a/pkg/testacc/data_source_listings_acceptance_test.go b/pkg/testacc/data_source_listings_acceptance_test.go new file mode 100644 index 0000000000..a85bcd0ffa --- /dev/null +++ b/pkg/testacc/data_source_listings_acceptance_test.go @@ -0,0 +1,195 @@ +//go:build non_account_level_tests + +package testacc + +import ( + "testing" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert/resourceshowoutputassert" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/config" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/config/datasourcemodel" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/config/model" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/config/providermodel" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/previewfeatures" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/resources" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/tfversion" +) + +func TestAcc_Listings_BasicUseCase_DifferentFiltering(t *testing.T) { + prefix := random.AlphaN(4) + idOne := testClient().Ids.RandomAccountObjectIdentifierWithPrefix(prefix + "1") + idTwo := testClient().Ids.RandomAccountObjectIdentifierWithPrefix(prefix + "2") + idThree := testClient().Ids.RandomAccountObjectIdentifier() + + manifest, _ := testClient().Listing.BasicManifestWithUnquotedValues(t) + + // Listings without share/app package cannot be published + listingModel1 := model.ListingWithInlineManifest("listing_1", idOne.Name(), manifest).WithPublish("false") + listingModel2 := model.ListingWithInlineManifest("listing_2", idTwo.Name(), manifest).WithPublish("false") + listingModel3 := model.ListingWithInlineManifest("listing_3", idThree.Name(), manifest).WithPublish("false") + + listingsLike := datasourcemodel.Listings("like"). + WithLike(idOne.Name()). + WithDependsOn(listingModel1.ResourceReference(), listingModel2.ResourceReference(), listingModel3.ResourceReference()) + + listingsStartsWith := datasourcemodel.Listings("test"). + WithStartsWith(prefix). + WithDependsOn(listingModel1.ResourceReference(), listingModel2.ResourceReference(), listingModel3.ResourceReference()) + + listingsLimit := datasourcemodel.Listings("test"). + WithRowsAndFrom(1, prefix). + WithDependsOn(listingModel1.ResourceReference(), listingModel2.ResourceReference(), listingModel3.ResourceReference()) + + providerModel := providermodel.SnowflakeProvider(). + WithPreviewFeaturesEnabled(string(previewfeatures.ListingsDatasource)) + + resource.Test(t, resource.TestCase{ + ProtoV6ProviderFactories: TestAccProtoV6ProviderFactories, + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.RequireAbove(tfversion.Version1_5_0), + }, + Steps: []resource.TestStep{ + { + Config: config.FromModels(t, providerModel, listingModel1, listingModel2, listingModel3, listingsLike), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(listingsLike.DatasourceReference(), "listings.#", "1"), + resource.TestCheckResourceAttr(listingsLike.DatasourceReference(), "listings.0.show_output.#", "1"), + resource.TestCheckResourceAttr(listingsLike.DatasourceReference(), "listings.0.show_output.0.name", idOne.Name()), + ), + }, + { + Config: config.FromModels(t, providerModel, listingModel1, listingModel2, listingModel3, listingsStartsWith), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(listingsStartsWith.DatasourceReference(), "listings.#", "2"), + ), + }, + { + Config: config.FromModels(t, providerModel, listingModel1, listingModel2, listingModel3, listingsLimit), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(listingsLimit.DatasourceReference(), "listings.#", "1"), + ), + }, + }, + }) +} + +func TestAcc_Listings_CompleteUseCase(t *testing.T) { + id := testClient().Ids.RandomAccountObjectIdentifier() + comment := random.Comment() + + manifest, title := testClient().Listing.BasicManifestWithUnquotedValuesAndTargetAccounts(t) + + share, shareCleanup := testClient().Share.CreateShare(t) + t.Cleanup(shareCleanup) + t.Cleanup(testClient().Grant.GrantPrivilegeOnDatabaseToShare(t, testClient().Ids.DatabaseId(), share.ID(), []sdk.ObjectPrivilege{sdk.ObjectPrivilegeUsage})) + + listingModel := model.ListingWithInlineManifest("listing_complete", id.Name(), manifest). + WithShare(share.ID().Name()). + WithPublish("true"). + WithComment(comment) + + listingsModelWithoutAdditional := datasourcemodel.Listings("without_additional"). + WithLike(id.Name()). + WithStartsWith(id.Name()). + WithLimit(1). + WithWithDescribe(false). + WithDependsOn(listingModel.ResourceReference()) + + listingsModel := datasourcemodel.Listings("with_additional"). + WithLike(id.Name()). + WithStartsWith(id.Name()). + WithLimit(1). + WithDependsOn(listingModel.ResourceReference()) + + providerModel := providermodel.SnowflakeProvider(). + WithPreviewFeaturesEnabled(string(previewfeatures.ListingsDatasource)) + + resource.Test(t, resource.TestCase{ + ProtoV6ProviderFactories: TestAccProtoV6ProviderFactories, + TerraformVersionChecks: []tfversion.TerraformVersionCheck{ + tfversion.RequireAbove(tfversion.Version1_5_0), + }, + CheckDestroy: CheckDestroy(t, resources.Listing), + Steps: []resource.TestStep{ + { + Config: config.FromModels(t, providerModel, listingModel, listingsModelWithoutAdditional), + Check: assertThat(t, + resourceshowoutputassert.ListingsDatasourceShowOutput(t, listingsModelWithoutAdditional.DatasourceReference()). + HasName(id.Name()). + HasTitle(title). + HasState(sdk.ListingStatePublished). + HasComment(comment), + + assert.Check(resource.TestCheckResourceAttr(listingsModelWithoutAdditional.DatasourceReference(), "listings.0.describe_output.#", "0")), + ), + }, + { + Config: config.FromModels(t, providerModel, listingModel, listingsModel), + Check: assertThat(t, + resourceshowoutputassert.ListingsDatasourceShowOutput(t, listingsModel.DatasourceReference()). + HasName(id.Name()). + HasTitle(title). + HasState(sdk.ListingStatePublished). + HasComment(comment), + + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.#", "1")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.name", id.Name())), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.title", title)), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.description", "description")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.created_on")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.updated_on")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.owner")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.owner_role_type")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.state", "PUBLISHED")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.share", share.ID().Name())), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.application_package", "")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.manifest_yaml")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.listing_terms")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.business_needs", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.usage_examples", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.data_attributes", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.categories", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.resources", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.profile", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.customized_contact_info", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.data_dictionary", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.data_preview", "")), + assert.Check(resource.TestCheckResourceAttrSet(listingsModel.DatasourceReference(), "listings.0.describe_output.0.published_on")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.comment", comment)), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.revisions", "PUBLISHED")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.target_accounts", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.regions", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.refresh_schedule", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.refresh_type", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.review_state", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.rejection_reason", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.unpublished_by_admin_reasons", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_monetized", "false")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_application", "false")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_targeted", "true")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_limited_trial", "false")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_by_request", "false")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.limited_trial_plan", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.retried_on", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.scheduled_drop_time", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.distribution", "EXTERNAL")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_mountless_queryable", "false")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.organization_profile_name", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.uniform_listing_locator", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.approver_contact", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.support_contact", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.published_version_name", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.published_version_alias", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.is_share", "true")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.request_approval_type", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.monetization_display_order", "")), + assert.Check(resource.TestCheckResourceAttr(listingsModel.DatasourceReference(), "listings.0.describe_output.0.legacy_uniform_listing_locators", "")), + ), + }, + }, + }) +} diff --git a/templates/data-sources/listings.md.tmpl b/templates/data-sources/listings.md.tmpl new file mode 100644 index 0000000000..04485a8518 --- /dev/null +++ b/templates/data-sources/listings.md.tmpl @@ -0,0 +1,29 @@ +--- +page_title: "{{.Name}} {{.Type}} - {{.ProviderName}}" +subcategory: "Preview" +description: |- +{{ if gt (len (split .Description "")) 1 -}} +{{ index (split .Description "") 1 | plainmarkdown | trimspace | prefixlines " " }} +{{- else -}} +{{ .Description | plainmarkdown | trimspace | prefixlines " " }} +{{- end }} +--- + +!> **Preview Feature** This data source is a preview feature and is subject to breaking changes, even without bumping the major version. To use this feature, add `snowflake_listings_datasource` to `preview_features_enabled` field in the provider configuration. Read more about preview features in our [documentation](../#preview-features). + +-> **Note** This data source focuses on base query commands (SHOW LISTINGS and DESCRIBE LISTING). Other query commands like SHOW AVAILABLE LISTINGS, DESCRIBE AVAILABLE LISTING, SHOW LISTING OFFERS, SHOW OFFERS, SHOW PRICING PLANS, and SHOW VERSIONS IN LISTING are not included and will be added depending on demand. + +# {{.Name}} ({{.Type}}) + +{{ .Description | trimspace }} + +{{ if .HasExample -}} +## Example Usage + +{{ tffile (printf "examples/data-sources/%s/data-source.tf" .Name)}} +{{- end }} + +-> **Note** If a field has a default value, it is shown next to the type in the schema. + +{{ .SchemaMarkdown | trimspace }} +