diff --git a/docs/resources/shared_database.md b/docs/resources/shared_database.md index 0ed981c871..09cf18a2fc 100644 --- a/docs/resources/shared_database.md +++ b/docs/resources/shared_database.md @@ -51,8 +51,6 @@ resource "snowflake_shared_database" "test" { from_share = "..${snowflake_share.test.name}" comment = "A shared database" - data_retention_time_in_days = 10 - max_data_extension_time_in_days = 20 external_volume = "" catalog = "" replace_invalid_characters = false diff --git a/examples/resources/snowflake_shared_database/resource.tf b/examples/resources/snowflake_shared_database/resource.tf index 9128bfaacf..5e6c14dc9d 100644 --- a/examples/resources/snowflake_shared_database/resource.tf +++ b/examples/resources/snowflake_shared_database/resource.tf @@ -35,8 +35,6 @@ resource "snowflake_shared_database" "test" { from_share = "..${snowflake_share.test.name}" comment = "A shared database" - data_retention_time_in_days = 10 - max_data_extension_time_in_days = 20 external_volume = "" catalog = "" replace_invalid_characters = false diff --git a/pkg/acceptance/bettertestspoc/README.md b/pkg/acceptance/bettertestspoc/README.md index 1ddb5311c2..a97717c232 100644 --- a/pkg/acceptance/bettertestspoc/README.md +++ b/pkg/acceptance/bettertestspoc/README.md @@ -342,3 +342,10 @@ func (w *WarehouseDatasourceShowOutputAssert) IsEmpty() { - support the rest of attribute types in config model builders (TODO left in `config/model/gen/model.go`) - parametrize test client helper used - integration versus acceptance tests - this has to be changed in the generator too (TODO left in `assert/objectassert/user_snowflake_ext.go`) - Omit computed fields in the model (like FullyQualifiedName), because it doesn't make sense to set them +- There's an error when generating models, steps to reproduce: + - Go to view resource code and change `data_metric_function` field to `testing` and make it required + - During the generation, the following error appears: mixed named and unnamed parameters. + It's a golang error indicating that the parameter has both unnamed and named parameters in function (e.g. `func(abc string, int)`). + The error is a result of both things: + 1. Lists of objects are partially generated, and only parameter name is generated in some functions (the type has to be added manually). + 2. `testing` is a package name that makes Go think that we want to have unnamed parameter there, but we just didn't generate the type for that field in the function argument. diff --git a/pkg/acceptance/bettertestspoc/assert/objectassert/gen/sdk_object_def.go b/pkg/acceptance/bettertestspoc/assert/objectassert/gen/sdk_object_def.go index c0da90f4cd..e26af08cef 100644 --- a/pkg/acceptance/bettertestspoc/assert/objectassert/gen/sdk_object_def.go +++ b/pkg/acceptance/bettertestspoc/assert/objectassert/gen/sdk_object_def.go @@ -52,6 +52,11 @@ var allStructs = []SdkObjectDef{ ObjectType: sdk.ObjectTypeAuthenticationPolicy, ObjectStruct: sdk.AuthenticationPolicy{}, }, + { + IdType: "sdk.SchemaObjectIdentifier", + ObjectType: sdk.ObjectTypeTask, + ObjectStruct: sdk.Task{}, + }, } func GetSdkObjectDetails() []genhelpers.SdkObjectDetails { diff --git a/pkg/acceptance/bettertestspoc/assert/objectassert/task_snowflake_ext.go b/pkg/acceptance/bettertestspoc/assert/objectassert/task_snowflake_ext.go new file mode 100644 index 0000000000..40f5894ba3 --- /dev/null +++ b/pkg/acceptance/bettertestspoc/assert/objectassert/task_snowflake_ext.go @@ -0,0 +1,74 @@ +package objectassert + +import ( + "errors" + "fmt" + "reflect" + "slices" + "testing" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" +) + +func (t *TaskAssert) HasNotEmptyCreatedOn() *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.CreatedOn == "" { + return fmt.Errorf("expected created on not empty; got: %v", o.CreatedOn) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasNotEmptyId() *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Id == "" { + return fmt.Errorf("expected id not empty; got: %v", o.CreatedOn) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasPredecessors(ids ...sdk.SchemaObjectIdentifier) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if len(o.Predecessors) != len(ids) { + return fmt.Errorf("expected %d (%v) predecessors, got %d (%v)", len(ids), ids, len(o.Predecessors), o.Predecessors) + } + var errs []error + for _, id := range ids { + if !slices.ContainsFunc(o.Predecessors, func(predecessorId sdk.SchemaObjectIdentifier) bool { + return predecessorId.FullyQualifiedName() == id.FullyQualifiedName() + }) { + errs = append(errs, fmt.Errorf("expected id: %s, to be in the list of predecessors: %v", id.FullyQualifiedName(), o.Predecessors)) + } + } + return errors.Join(errs...) + }) + return t +} + +func (t *TaskAssert) HasTaskRelations(expected sdk.TaskRelations) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if len(o.TaskRelations.Predecessors) != len(expected.Predecessors) { + return fmt.Errorf("expected %d (%v) predecessors in task relations, got %d (%v)", len(expected.Predecessors), expected.Predecessors, len(o.TaskRelations.Predecessors), o.TaskRelations.Predecessors) + } + var errs []error + for _, id := range expected.Predecessors { + if !slices.ContainsFunc(o.TaskRelations.Predecessors, func(predecessorId sdk.SchemaObjectIdentifier) bool { + return predecessorId.FullyQualifiedName() == id.FullyQualifiedName() + }) { + errs = append(errs, fmt.Errorf("expected id: %s, to be in the list of predecessors in task relations: %v", id.FullyQualifiedName(), o.TaskRelations.Predecessors)) + } + } + if !reflect.DeepEqual(expected.FinalizerTask, o.TaskRelations.FinalizerTask) { + errs = append(errs, fmt.Errorf("expected finalizer task: %v; got: %v", expected.FinalizerTask, o.TaskRelations.FinalizerTask)) + } + return errors.Join(errs...) + }) + return t +} diff --git a/pkg/acceptance/bettertestspoc/assert/objectassert/task_snowflake_gen.go b/pkg/acceptance/bettertestspoc/assert/objectassert/task_snowflake_gen.go new file mode 100644 index 0000000000..c0180747ab --- /dev/null +++ b/pkg/acceptance/bettertestspoc/assert/objectassert/task_snowflake_gen.go @@ -0,0 +1,251 @@ +// Code generated by assertions generator; DO NOT EDIT. + +package objectassert + +import ( + "fmt" + "testing" + + acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" +) + +type TaskAssert struct { + *assert.SnowflakeObjectAssert[sdk.Task, sdk.SchemaObjectIdentifier] +} + +func Task(t *testing.T, id sdk.SchemaObjectIdentifier) *TaskAssert { + t.Helper() + return &TaskAssert{ + assert.NewSnowflakeObjectAssertWithProvider(sdk.ObjectTypeTask, id, acc.TestClient().Task.Show), + } +} + +func TaskFromObject(t *testing.T, task *sdk.Task) *TaskAssert { + t.Helper() + return &TaskAssert{ + assert.NewSnowflakeObjectAssertWithObject(sdk.ObjectTypeTask, task.ID(), task), + } +} + +func (t *TaskAssert) HasCreatedOn(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.CreatedOn != expected { + return fmt.Errorf("expected created on: %v; got: %v", expected, o.CreatedOn) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasName(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Name != expected { + return fmt.Errorf("expected name: %v; got: %v", expected, o.Name) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasId(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Id != expected { + return fmt.Errorf("expected id: %v; got: %v", expected, o.Id) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasDatabaseName(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.DatabaseName != expected { + return fmt.Errorf("expected database name: %v; got: %v", expected, o.DatabaseName) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasSchemaName(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.SchemaName != expected { + return fmt.Errorf("expected schema name: %v; got: %v", expected, o.SchemaName) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasOwner(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Owner != expected { + return fmt.Errorf("expected owner: %v; got: %v", expected, o.Owner) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasComment(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Comment != expected { + return fmt.Errorf("expected comment: %v; got: %v", expected, o.Comment) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasWarehouse(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Warehouse != expected { + return fmt.Errorf("expected warehouse: %v; got: %v", expected, o.Warehouse) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasSchedule(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Schedule != expected { + return fmt.Errorf("expected schedule: %v; got: %v", expected, o.Schedule) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasState(expected sdk.TaskState) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.State != expected { + return fmt.Errorf("expected state: %v; got: %v", expected, o.State) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasDefinition(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Definition != expected { + return fmt.Errorf("expected definition: %v; got: %v", expected, o.Definition) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasCondition(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Condition != expected { + return fmt.Errorf("expected condition: %v; got: %v", expected, o.Condition) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasAllowOverlappingExecution(expected bool) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.AllowOverlappingExecution != expected { + return fmt.Errorf("expected allow overlapping execution: %v; got: %v", expected, o.AllowOverlappingExecution) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasErrorIntegration(expected *sdk.AccountObjectIdentifier) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.ErrorIntegration != expected { + return fmt.Errorf("expected error integration: %v; got: %v", expected, o.ErrorIntegration) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasLastCommittedOn(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.LastCommittedOn != expected { + return fmt.Errorf("expected last committed on: %v; got: %v", expected, o.LastCommittedOn) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasLastSuspendedOn(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.LastSuspendedOn != expected { + return fmt.Errorf("expected last suspended on: %v; got: %v", expected, o.LastSuspendedOn) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasOwnerRoleType(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.OwnerRoleType != expected { + return fmt.Errorf("expected owner role type: %v; got: %v", expected, o.OwnerRoleType) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasConfig(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Config != expected { + return fmt.Errorf("expected config: %v; got: %v", expected, o.Config) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasBudget(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.Budget != expected { + return fmt.Errorf("expected budget: %v; got: %v", expected, o.Budget) + } + return nil + }) + return t +} + +func (t *TaskAssert) HasLastSuspendedReason(expected string) *TaskAssert { + t.AddAssertion(func(t *testing.T, o *sdk.Task) error { + t.Helper() + if o.LastSuspendedReason != expected { + return fmt.Errorf("expected last suspended reason: %v; got: %v", expected, o.LastSuspendedReason) + } + return nil + }) + return t +} diff --git a/pkg/acceptance/bettertestspoc/assert/objectparametersassert/gen/object_parameters_def.go b/pkg/acceptance/bettertestspoc/assert/objectparametersassert/gen/object_parameters_def.go index b87151ccae..a2141417ff 100644 --- a/pkg/acceptance/bettertestspoc/assert/objectparametersassert/gen/object_parameters_def.go +++ b/pkg/acceptance/bettertestspoc/assert/objectparametersassert/gen/object_parameters_def.go @@ -128,4 +128,136 @@ var allObjectsParameters = []SnowflakeObjectParameters{ {ParameterName: string(sdk.DatabaseParameterEnableConsoleOutput), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, }, }, + { + Name: "Task", + IdType: "sdk.SchemaObjectIdentifier", + Level: sdk.ParameterTypeTask, + Parameters: []SnowflakeParameter{ + // ABORT_DETACHED_QUERY + // ACTIVE_PYTHON_PROFILER + {ParameterName: string(sdk.TaskParameterAutocommit), ParameterType: "bool", DefaultValue: "true", DefaultLevel: "sdk.ParameterTypeAccount"}, + // AUTOCOMMIT_API_SUPPORTED + {ParameterName: string(sdk.TaskParameterBinaryInputFormat), ParameterType: "sdk.BinaryInputFormat", DefaultValue: "sdk.BinaryInputFormatHex", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterBinaryOutputFormat), ParameterType: "sdk.BinaryOutputFormat", DefaultValue: "sdk.BinaryOutputFormatHex", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // CLIENT_ENABLE_CONSERVATIVE_MEMORY_USAGE + // CLIENT_ENABLE_DEFAULT_OVERWRITE_IN_PUT + // CLIENT_ENABLE_LOG_INFO_STATEMENT_PARAMETERS + {ParameterName: string(sdk.TaskParameterClientMemoryLimit), ParameterType: "int", DefaultValue: "1536", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterClientMetadataRequestUseConnectionCtx), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // CLIENT_METADATA_USE_SESSION_DATABASE + {ParameterName: string(sdk.TaskParameterClientPrefetchThreads), ParameterType: "int", DefaultValue: "4", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterClientResultChunkSize), ParameterType: "int", DefaultValue: "160", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterClientResultColumnCaseInsensitive), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // CLIENT_SESSION_CLONE + {ParameterName: string(sdk.TaskParameterClientSessionKeepAlive), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterClientSessionKeepAliveHeartbeatFrequency), ParameterType: "int", DefaultValue: "3600", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterClientTimestampTypeMapping), ParameterType: "sdk.ClientTimestampTypeMapping", DefaultValue: "sdk.ClientTimestampTypeMappingLtz", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // CSV_TIMESTAMP_FORMAT + // C_API_QUERY_RESULT_FORMAT + {ParameterName: string(sdk.TaskParameterDateInputFormat), ParameterType: "string", DefaultValue: "AUTO", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterDateOutputFormat), ParameterType: "string", DefaultValue: "YYYY-MM-DD", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // DOTNET_QUERY_RESULT_FORMAT + // DYNAMIC_TABLES_VIEW_VERSION + // DYNAMIC_TABLE_GRAPH_HISTORY_VIEW_VERSION + // DYNAMIC_TABLE_REFRESH_HISTORY_VIEW_VERSION + // ENABLE_CONSOLE_OUTPUT + // ENABLE_PROVIDER_LISTING_PROGRAMMATIC_ACCESS_DESCRIBE_LISTING + // ENABLE_SNOW_API_FOR_COMPUTE_POOL + // ENABLE_SNOW_API_FOR_COPILOT + // ENABLE_SNOW_API_FOR_DATABASE + // ENABLE_SNOW_API_FOR_FUNCTION + // ENABLE_SNOW_API_FOR_GRANT + // ENABLE_SNOW_API_FOR_ICEBERG + // ENABLE_SNOW_API_FOR_IMAGE_REPOSITORY + // ENABLE_SNOW_API_FOR_RESULT + // ENABLE_SNOW_API_FOR_ROLE + // ENABLE_SNOW_API_FOR_SCHEMA + // ENABLE_SNOW_API_FOR_SERVICE + // ENABLE_SNOW_API_FOR_SESSION + // ENABLE_SNOW_API_FOR_STAGE + // ENABLE_SNOW_API_FOR_TABLE + // ENABLE_SNOW_API_FOR_TASK + // ENABLE_SNOW_API_FOR_USER + // ENABLE_SNOW_API_FOR_WAREHOUSE + {ParameterName: string(sdk.TaskParameterEnableUnloadPhysicalTypeOptimization), ParameterType: "bool", DefaultValue: "true", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterErrorOnNondeterministicMerge), ParameterType: "bool", DefaultValue: "true", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterErrorOnNondeterministicUpdate), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterGeographyOutputFormat), ParameterType: "sdk.GeographyOutputFormat", DefaultValue: "sdk.GeographyOutputFormatGeoJSON", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterGeometryOutputFormat), ParameterType: "sdk.GeometryOutputFormat", DefaultValue: "sdk.GeometryOutputFormatGeoJSON", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // GO_QUERY_RESULT_FORMAT + // HYBRID_TABLE_LOCK_TIMEOUT + // INCLUDE_DT_WITH_TABLE_KIND_IN_SHOW_OBJECTS + // INCLUDE_DYNAMIC_TABLES_WITH_TABLE_KIND + // JDBC_FORMAT_DATE_WITH_TIMEZONE + // JDBC_QUERY_RESULT_FORMAT + {ParameterName: string(sdk.TaskParameterJdbcTreatTimestampNtzAsUtc), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterJdbcUseSessionTimezone), ParameterType: "bool", DefaultValue: "true", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterJsonIndent), ParameterType: "int", DefaultValue: "2", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // LANGUAGE + {ParameterName: string(sdk.TaskParameterLockTimeout), ParameterType: "int", DefaultValue: "43200", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterLogLevel), ParameterType: "sdk.LogLevel", DefaultValue: "sdk.LogLevelOff", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // METRIC_LEVEL + {ParameterName: string(sdk.TaskParameterMultiStatementCount), ParameterType: "int", DefaultValue: "1", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterNoorderSequenceAsDefault), ParameterType: "bool", DefaultValue: "true", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // ODBC_QUERY_RESULT_FORMAT + {ParameterName: string(sdk.TaskParameterOdbcTreatDecimalAsInt), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // PYTHON_CONNECTOR_QUERY_RESULT_FORMAT + // PYTHON_CONNECTOR_USE_NANOARROW + // PYTHON_PROFILER_MODULES + // PYTHON_PROFILER_TARGET_STAGE + // PYTHON_SNOWPARK_AUTO_CLEAN_UP_TEMP_TABLE_ENABLED + // PYTHON_SNOWPARK_COMPILATION_STAGE_ENABLED + // PYTHON_SNOWPARK_ELIMINATE_NUMERIC_SQL_VALUE_CAST_ENABLED + // PYTHON_SNOWPARK_USE_CTE_OPTIMIZATION + // PYTHON_SNOWPARK_USE_LARGE_QUERY_BREAKDOWN_OPTIMIZATION + // PYTHON_SNOWPARK_USE_LOGICAL_TYPE_FOR_CREATE_DATAFRAME + // PYTHON_SNOWPARK_USE_SCOPED_TEMP_OBJECTS + // PYTHON_SNOWPARK_USE_SQL_SIMPLIFIER + // QA_TEST_NAME + // QUERY_RESULT_FORMAT + {ParameterName: string(sdk.TaskParameterQueryTag), ParameterType: "string", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterQuotedIdentifiersIgnoreCase), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeAccount"}, + {ParameterName: string(sdk.TaskParameterRowsPerResultset), ParameterType: "int", DefaultValue: "0", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterS3StageVpceDnsName), ParameterType: "string", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterSearchPath), ParameterType: "string", DefaultValue: "$current, $public", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // SHOW_EXTERNAL_TABLE_KIND_AS_TABLE + // SNOWPARK_HIDE_INTERNAL_ALIAS + // SNOWPARK_LAZY_ANALYSIS + // SNOWPARK_REQUEST_TIMEOUT_IN_SECONDS + // SNOWPARK_STORED_PROC_IS_FINAL_TABLE_QUERY + // SNOWPARK_USE_SCOPED_TEMP_OBJECTS + // SQL_API_NULLABLE_IN_RESULT_SET + // SQL_API_QUERY_RESULT_FORMAT + {ParameterName: string(sdk.TaskParameterStatementQueuedTimeoutInSeconds), ParameterType: "int", DefaultValue: "0", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterStatementTimeoutInSeconds), ParameterType: "int", DefaultValue: "172800", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterStrictJsonOutput), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // TODO: SUSPEND_TASK_AFTER_NUM_FAILURES + // TODO: TASK_AUTO_RETRY_ATTEMPTS + {ParameterName: string(sdk.TaskParameterTimestampDayIsAlways24h), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimestampInputFormat), ParameterType: "string", DefaultValue: "AUTO", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimestampLtzOutputFormat), ParameterType: "string", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimestampNtzOutputFormat), ParameterType: "string", DefaultValue: "YYYY-MM-DD HH24:MI:SS.FF3", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimestampOutputFormat), ParameterType: "string", DefaultValue: "YYYY-MM-DD HH24:MI:SS.FF3 TZHTZM", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimestampTypeMapping), ParameterType: "sdk.TimestampTypeMapping", DefaultValue: "sdk.TimestampTypeMappingNtz", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimestampTzOutputFormat), ParameterType: "string", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimezone), ParameterType: "string", DefaultValue: "America/Los_Angeles", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimeInputFormat), ParameterType: "string", DefaultValue: "AUTO", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTimeOutputFormat), ParameterType: "string", DefaultValue: "HH24:MI:SS", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTraceLevel), ParameterType: "sdk.TraceLevel", DefaultValue: "sdk.TraceLevelOff", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTransactionAbortOnError), ParameterType: "bool", DefaultValue: "false", DefaultLevel: "sdk.ParameterTypeAccount"}, + {ParameterName: string(sdk.TaskParameterTransactionDefaultIsolationLevel), ParameterType: "sdk.TransactionDefaultIsolationLevel", DefaultValue: "sdk.TransactionDefaultIsolationLevelReadCommitted", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterTwoDigitCenturyStart), ParameterType: "int", DefaultValue: "1970", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // TODO UI_QUERY_RESULT_FORMAT + // TODO [SNOW-1501905]: quick workaround for now: lowercase for ignore in snowflake by default but uppercase for FAIL + {ParameterName: string(sdk.TaskParameterUnsupportedDdlAction), ParameterType: "sdk.UnsupportedDDLAction", DefaultValue: "sdk.UnsupportedDDLAction(strings.ToLower(string(sdk.UnsupportedDDLActionIgnore)))", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterUserTaskManagedInitialWarehouseSize), ParameterType: "sdk.WarehouseSize", DefaultValue: "Medium", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // {ParameterName: string(sdk.UserParameterUnsupportedUserTaskMinimumTriggerIntervalInSeconds), ParameterType: "int", DefaultValue: "30", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + // {ParameterName: string(sdk.UserParameterUnsupportedUserTaskTimeoutMs), ParameterType: "int", DefaultValue: "3600000", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterUseCachedResult), ParameterType: "bool", DefaultValue: "true", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterWeekOfYearPolicy), ParameterType: "int", DefaultValue: "0", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + {ParameterName: string(sdk.TaskParameterWeekStart), ParameterType: "int", DefaultValue: "0", DefaultLevel: "sdk.ParameterTypeSnowflakeDefault"}, + }, + // for the quickfix above + AdditionalImports: []string{"strings"}, + }, } diff --git a/pkg/acceptance/bettertestspoc/assert/objectparametersassert/task_parameters_snowflake_gen.go b/pkg/acceptance/bettertestspoc/assert/objectparametersassert/task_parameters_snowflake_gen.go new file mode 100644 index 0000000000..8feaea52b1 --- /dev/null +++ b/pkg/acceptance/bettertestspoc/assert/objectparametersassert/task_parameters_snowflake_gen.go @@ -0,0 +1,1151 @@ +// Code generated by assertions generator; DO NOT EDIT. + +package objectparametersassert + +import ( + "strings" + "testing" + + acc "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" +) + +type TaskParametersAssert struct { + *assert.SnowflakeParametersAssert[sdk.SchemaObjectIdentifier] +} + +func TaskParameters(t *testing.T, id sdk.SchemaObjectIdentifier) *TaskParametersAssert { + t.Helper() + return &TaskParametersAssert{ + assert.NewSnowflakeParametersAssertWithProvider(id, sdk.ObjectTypeTask, acc.TestClient().Parameter.ShowTaskParameters), + } +} + +func TaskParametersPrefetched(t *testing.T, id sdk.SchemaObjectIdentifier, parameters []*sdk.Parameter) *TaskParametersAssert { + t.Helper() + return &TaskParametersAssert{ + assert.NewSnowflakeParametersAssertWithParameters(id, sdk.ObjectTypeTask, parameters), + } +} + +////////////////////////////// +// Generic parameter checks // +////////////////////////////// + +func (t *TaskParametersAssert) HasBoolParameterValue(parameterName sdk.TaskParameter, expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(parameterName, expected)) + return t +} + +func (t *TaskParametersAssert) HasIntParameterValue(parameterName sdk.TaskParameter, expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(parameterName, expected)) + return t +} + +func (t *TaskParametersAssert) HasStringParameterValue(parameterName sdk.TaskParameter, expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(parameterName, expected)) + return t +} + +func (t *TaskParametersAssert) HasDefaultParameterValue(parameterName sdk.TaskParameter) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterDefaultValueSet(parameterName)) + return t +} + +func (t *TaskParametersAssert) HasDefaultParameterValueOnLevel(parameterName sdk.TaskParameter, parameterType sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterDefaultValueOnLevelSet(parameterName, parameterType)) + return t +} + +/////////////////////////////// +// Aggregated generic checks // +/////////////////////////////// + +// HasAllDefaults checks if all the parameters: +// - have a default value by comparing current value of the sdk.Parameter with its default +// - have an expected level +func (t *TaskParametersAssert) HasAllDefaults() *TaskParametersAssert { + return t. + HasDefaultParameterValueOnLevel(sdk.TaskParameterAutocommit, sdk.ParameterTypeAccount). + HasDefaultParameterValueOnLevel(sdk.TaskParameterBinaryInputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterBinaryOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientMemoryLimit, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientMetadataRequestUseConnectionCtx, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientPrefetchThreads, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientResultChunkSize, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientResultColumnCaseInsensitive, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientSessionKeepAlive, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientSessionKeepAliveHeartbeatFrequency, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterClientTimestampTypeMapping, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterDateInputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterDateOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterEnableUnloadPhysicalTypeOptimization, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterErrorOnNondeterministicMerge, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterErrorOnNondeterministicUpdate, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterGeographyOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterGeometryOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterJdbcTreatTimestampNtzAsUtc, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterJdbcUseSessionTimezone, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterJsonIndent, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterLockTimeout, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterLogLevel, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterMultiStatementCount, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterNoorderSequenceAsDefault, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterOdbcTreatDecimalAsInt, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterQueryTag, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterQuotedIdentifiersIgnoreCase, sdk.ParameterTypeAccount). + HasDefaultParameterValueOnLevel(sdk.TaskParameterRowsPerResultset, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterS3StageVpceDnsName, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterSearchPath, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterStatementQueuedTimeoutInSeconds, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterStatementTimeoutInSeconds, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterStrictJsonOutput, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampDayIsAlways24h, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampInputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampLtzOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampNtzOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampTypeMapping, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimestampTzOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimezone, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimeInputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTimeOutputFormat, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTraceLevel, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTransactionAbortOnError, sdk.ParameterTypeAccount). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTransactionDefaultIsolationLevel, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterTwoDigitCenturyStart, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterUnsupportedDdlAction, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterUserTaskManagedInitialWarehouseSize, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterUseCachedResult, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterWeekOfYearPolicy, sdk.ParameterTypeSnowflakeDefault). + HasDefaultParameterValueOnLevel(sdk.TaskParameterWeekStart, sdk.ParameterTypeSnowflakeDefault) +} + +func (t *TaskParametersAssert) HasAllDefaultsExplicit() *TaskParametersAssert { + return t. + HasDefaultAutocommitValueExplicit(). + HasDefaultBinaryInputFormatValueExplicit(). + HasDefaultBinaryOutputFormatValueExplicit(). + HasDefaultClientMemoryLimitValueExplicit(). + HasDefaultClientMetadataRequestUseConnectionCtxValueExplicit(). + HasDefaultClientPrefetchThreadsValueExplicit(). + HasDefaultClientResultChunkSizeValueExplicit(). + HasDefaultClientResultColumnCaseInsensitiveValueExplicit(). + HasDefaultClientSessionKeepAliveValueExplicit(). + HasDefaultClientSessionKeepAliveHeartbeatFrequencyValueExplicit(). + HasDefaultClientTimestampTypeMappingValueExplicit(). + HasDefaultDateInputFormatValueExplicit(). + HasDefaultDateOutputFormatValueExplicit(). + HasDefaultEnableUnloadPhysicalTypeOptimizationValueExplicit(). + HasDefaultErrorOnNondeterministicMergeValueExplicit(). + HasDefaultErrorOnNondeterministicUpdateValueExplicit(). + HasDefaultGeographyOutputFormatValueExplicit(). + HasDefaultGeometryOutputFormatValueExplicit(). + HasDefaultJdbcTreatTimestampNtzAsUtcValueExplicit(). + HasDefaultJdbcUseSessionTimezoneValueExplicit(). + HasDefaultJsonIndentValueExplicit(). + HasDefaultLockTimeoutValueExplicit(). + HasDefaultLogLevelValueExplicit(). + HasDefaultMultiStatementCountValueExplicit(). + HasDefaultNoorderSequenceAsDefaultValueExplicit(). + HasDefaultOdbcTreatDecimalAsIntValueExplicit(). + HasDefaultQueryTagValueExplicit(). + HasDefaultQuotedIdentifiersIgnoreCaseValueExplicit(). + HasDefaultRowsPerResultsetValueExplicit(). + HasDefaultS3StageVpceDnsNameValueExplicit(). + HasDefaultSearchPathValueExplicit(). + HasDefaultStatementQueuedTimeoutInSecondsValueExplicit(). + HasDefaultStatementTimeoutInSecondsValueExplicit(). + HasDefaultStrictJsonOutputValueExplicit(). + HasDefaultTimestampDayIsAlways24hValueExplicit(). + HasDefaultTimestampInputFormatValueExplicit(). + HasDefaultTimestampLtzOutputFormatValueExplicit(). + HasDefaultTimestampNtzOutputFormatValueExplicit(). + HasDefaultTimestampOutputFormatValueExplicit(). + HasDefaultTimestampTypeMappingValueExplicit(). + HasDefaultTimestampTzOutputFormatValueExplicit(). + HasDefaultTimezoneValueExplicit(). + HasDefaultTimeInputFormatValueExplicit(). + HasDefaultTimeOutputFormatValueExplicit(). + HasDefaultTraceLevelValueExplicit(). + HasDefaultTransactionAbortOnErrorValueExplicit(). + HasDefaultTransactionDefaultIsolationLevelValueExplicit(). + HasDefaultTwoDigitCenturyStartValueExplicit(). + HasDefaultUnsupportedDdlActionValueExplicit(). + HasDefaultUserTaskManagedInitialWarehouseSizeValueExplicit(). + HasDefaultUseCachedResultValueExplicit(). + HasDefaultWeekOfYearPolicyValueExplicit(). + HasDefaultWeekStartValueExplicit() +} + +//////////////////////////// +// Parameter value checks // +//////////////////////////// + +func (t *TaskParametersAssert) HasAutocommit(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterAutocommit, expected)) + return t +} + +func (t *TaskParametersAssert) HasBinaryInputFormat(expected sdk.BinaryInputFormat) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterBinaryInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasBinaryOutputFormat(expected sdk.BinaryOutputFormat) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterBinaryOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientMemoryLimit(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterClientMemoryLimit, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientMetadataRequestUseConnectionCtx(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterClientMetadataRequestUseConnectionCtx, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientPrefetchThreads(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterClientPrefetchThreads, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientResultChunkSize(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterClientResultChunkSize, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientResultColumnCaseInsensitive(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterClientResultColumnCaseInsensitive, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientSessionKeepAlive(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterClientSessionKeepAlive, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientSessionKeepAliveHeartbeatFrequency(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterClientSessionKeepAliveHeartbeatFrequency, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientTimestampTypeMapping(expected sdk.ClientTimestampTypeMapping) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterClientTimestampTypeMapping, expected)) + return t +} + +func (t *TaskParametersAssert) HasDateInputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterDateInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasDateOutputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterDateOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasEnableUnloadPhysicalTypeOptimization(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterEnableUnloadPhysicalTypeOptimization, expected)) + return t +} + +func (t *TaskParametersAssert) HasErrorOnNondeterministicMerge(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterErrorOnNondeterministicMerge, expected)) + return t +} + +func (t *TaskParametersAssert) HasErrorOnNondeterministicUpdate(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterErrorOnNondeterministicUpdate, expected)) + return t +} + +func (t *TaskParametersAssert) HasGeographyOutputFormat(expected sdk.GeographyOutputFormat) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterGeographyOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasGeometryOutputFormat(expected sdk.GeometryOutputFormat) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterGeometryOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasJdbcTreatTimestampNtzAsUtc(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterJdbcTreatTimestampNtzAsUtc, expected)) + return t +} + +func (t *TaskParametersAssert) HasJdbcUseSessionTimezone(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterJdbcUseSessionTimezone, expected)) + return t +} + +func (t *TaskParametersAssert) HasJsonIndent(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterJsonIndent, expected)) + return t +} + +func (t *TaskParametersAssert) HasLockTimeout(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterLockTimeout, expected)) + return t +} + +func (t *TaskParametersAssert) HasLogLevel(expected sdk.LogLevel) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterLogLevel, expected)) + return t +} + +func (t *TaskParametersAssert) HasMultiStatementCount(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterMultiStatementCount, expected)) + return t +} + +func (t *TaskParametersAssert) HasNoorderSequenceAsDefault(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterNoorderSequenceAsDefault, expected)) + return t +} + +func (t *TaskParametersAssert) HasOdbcTreatDecimalAsInt(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterOdbcTreatDecimalAsInt, expected)) + return t +} + +func (t *TaskParametersAssert) HasQueryTag(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterQueryTag, expected)) + return t +} + +func (t *TaskParametersAssert) HasQuotedIdentifiersIgnoreCase(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterQuotedIdentifiersIgnoreCase, expected)) + return t +} + +func (t *TaskParametersAssert) HasRowsPerResultset(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterRowsPerResultset, expected)) + return t +} + +func (t *TaskParametersAssert) HasS3StageVpceDnsName(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterS3StageVpceDnsName, expected)) + return t +} + +func (t *TaskParametersAssert) HasSearchPath(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterSearchPath, expected)) + return t +} + +func (t *TaskParametersAssert) HasStatementQueuedTimeoutInSeconds(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterStatementQueuedTimeoutInSeconds, expected)) + return t +} + +func (t *TaskParametersAssert) HasStatementTimeoutInSeconds(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterStatementTimeoutInSeconds, expected)) + return t +} + +func (t *TaskParametersAssert) HasStrictJsonOutput(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterStrictJsonOutput, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampDayIsAlways24h(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterTimestampDayIsAlways24h, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampInputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimestampInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampLtzOutputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimestampLtzOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampNtzOutputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimestampNtzOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampOutputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimestampOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampTypeMapping(expected sdk.TimestampTypeMapping) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterTimestampTypeMapping, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampTzOutputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimestampTzOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimezone(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimezone, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimeInputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimeInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimeOutputFormat(expected string) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterValueSet(sdk.TaskParameterTimeOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTraceLevel(expected sdk.TraceLevel) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterTraceLevel, expected)) + return t +} + +func (t *TaskParametersAssert) HasTransactionAbortOnError(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterTransactionAbortOnError, expected)) + return t +} + +func (t *TaskParametersAssert) HasTransactionDefaultIsolationLevel(expected sdk.TransactionDefaultIsolationLevel) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterTransactionDefaultIsolationLevel, expected)) + return t +} + +func (t *TaskParametersAssert) HasTwoDigitCenturyStart(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterTwoDigitCenturyStart, expected)) + return t +} + +func (t *TaskParametersAssert) HasUnsupportedDdlAction(expected sdk.UnsupportedDDLAction) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterUnsupportedDdlAction, expected)) + return t +} + +func (t *TaskParametersAssert) HasUserTaskManagedInitialWarehouseSize(expected sdk.WarehouseSize) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterStringUnderlyingValueSet(sdk.TaskParameterUserTaskManagedInitialWarehouseSize, expected)) + return t +} + +func (t *TaskParametersAssert) HasUseCachedResult(expected bool) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterBoolValueSet(sdk.TaskParameterUseCachedResult, expected)) + return t +} + +func (t *TaskParametersAssert) HasWeekOfYearPolicy(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterWeekOfYearPolicy, expected)) + return t +} + +func (t *TaskParametersAssert) HasWeekStart(expected int) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterIntValueSet(sdk.TaskParameterWeekStart, expected)) + return t +} + +//////////////////////////// +// Parameter level checks // +//////////////////////////// + +func (t *TaskParametersAssert) HasAutocommitLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterAutocommit, expected)) + return t +} + +func (t *TaskParametersAssert) HasBinaryInputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterBinaryInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasBinaryOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterBinaryOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientMemoryLimitLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientMemoryLimit, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientMetadataRequestUseConnectionCtxLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientMetadataRequestUseConnectionCtx, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientPrefetchThreadsLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientPrefetchThreads, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientResultChunkSizeLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientResultChunkSize, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientResultColumnCaseInsensitiveLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientResultColumnCaseInsensitive, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientSessionKeepAliveLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientSessionKeepAlive, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientSessionKeepAliveHeartbeatFrequencyLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientSessionKeepAliveHeartbeatFrequency, expected)) + return t +} + +func (t *TaskParametersAssert) HasClientTimestampTypeMappingLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterClientTimestampTypeMapping, expected)) + return t +} + +func (t *TaskParametersAssert) HasDateInputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterDateInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasDateOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterDateOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasEnableUnloadPhysicalTypeOptimizationLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterEnableUnloadPhysicalTypeOptimization, expected)) + return t +} + +func (t *TaskParametersAssert) HasErrorOnNondeterministicMergeLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterErrorOnNondeterministicMerge, expected)) + return t +} + +func (t *TaskParametersAssert) HasErrorOnNondeterministicUpdateLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterErrorOnNondeterministicUpdate, expected)) + return t +} + +func (t *TaskParametersAssert) HasGeographyOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterGeographyOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasGeometryOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterGeometryOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasJdbcTreatTimestampNtzAsUtcLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterJdbcTreatTimestampNtzAsUtc, expected)) + return t +} + +func (t *TaskParametersAssert) HasJdbcUseSessionTimezoneLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterJdbcUseSessionTimezone, expected)) + return t +} + +func (t *TaskParametersAssert) HasJsonIndentLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterJsonIndent, expected)) + return t +} + +func (t *TaskParametersAssert) HasLockTimeoutLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterLockTimeout, expected)) + return t +} + +func (t *TaskParametersAssert) HasLogLevelLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterLogLevel, expected)) + return t +} + +func (t *TaskParametersAssert) HasMultiStatementCountLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterMultiStatementCount, expected)) + return t +} + +func (t *TaskParametersAssert) HasNoorderSequenceAsDefaultLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterNoorderSequenceAsDefault, expected)) + return t +} + +func (t *TaskParametersAssert) HasOdbcTreatDecimalAsIntLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterOdbcTreatDecimalAsInt, expected)) + return t +} + +func (t *TaskParametersAssert) HasQueryTagLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterQueryTag, expected)) + return t +} + +func (t *TaskParametersAssert) HasQuotedIdentifiersIgnoreCaseLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterQuotedIdentifiersIgnoreCase, expected)) + return t +} + +func (t *TaskParametersAssert) HasRowsPerResultsetLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterRowsPerResultset, expected)) + return t +} + +func (t *TaskParametersAssert) HasS3StageVpceDnsNameLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterS3StageVpceDnsName, expected)) + return t +} + +func (t *TaskParametersAssert) HasSearchPathLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterSearchPath, expected)) + return t +} + +func (t *TaskParametersAssert) HasStatementQueuedTimeoutInSecondsLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterStatementQueuedTimeoutInSeconds, expected)) + return t +} + +func (t *TaskParametersAssert) HasStatementTimeoutInSecondsLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterStatementTimeoutInSeconds, expected)) + return t +} + +func (t *TaskParametersAssert) HasStrictJsonOutputLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterStrictJsonOutput, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampDayIsAlways24hLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampDayIsAlways24h, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampInputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampLtzOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampLtzOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampNtzOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampNtzOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampTypeMappingLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampTypeMapping, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimestampTzOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimestampTzOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimezoneLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimezone, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimeInputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimeInputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTimeOutputFormatLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTimeOutputFormat, expected)) + return t +} + +func (t *TaskParametersAssert) HasTraceLevelLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTraceLevel, expected)) + return t +} + +func (t *TaskParametersAssert) HasTransactionAbortOnErrorLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTransactionAbortOnError, expected)) + return t +} + +func (t *TaskParametersAssert) HasTransactionDefaultIsolationLevelLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTransactionDefaultIsolationLevel, expected)) + return t +} + +func (t *TaskParametersAssert) HasTwoDigitCenturyStartLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterTwoDigitCenturyStart, expected)) + return t +} + +func (t *TaskParametersAssert) HasUnsupportedDdlActionLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterUnsupportedDdlAction, expected)) + return t +} + +func (t *TaskParametersAssert) HasUserTaskManagedInitialWarehouseSizeLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterUserTaskManagedInitialWarehouseSize, expected)) + return t +} + +func (t *TaskParametersAssert) HasUseCachedResultLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterUseCachedResult, expected)) + return t +} + +func (t *TaskParametersAssert) HasWeekOfYearPolicyLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterWeekOfYearPolicy, expected)) + return t +} + +func (t *TaskParametersAssert) HasWeekStartLevel(expected sdk.ParameterType) *TaskParametersAssert { + t.AddAssertion(assert.SnowflakeParameterLevelSet(sdk.TaskParameterWeekStart, expected)) + return t +} + +//////////////////////////////////// +// Parameter default value checks // +//////////////////////////////////// + +func (t *TaskParametersAssert) HasDefaultAutocommitValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterAutocommit) +} + +func (t *TaskParametersAssert) HasDefaultBinaryInputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterBinaryInputFormat) +} + +func (t *TaskParametersAssert) HasDefaultBinaryOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterBinaryOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultClientMemoryLimitValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientMemoryLimit) +} + +func (t *TaskParametersAssert) HasDefaultClientMetadataRequestUseConnectionCtxValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientMetadataRequestUseConnectionCtx) +} + +func (t *TaskParametersAssert) HasDefaultClientPrefetchThreadsValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientPrefetchThreads) +} + +func (t *TaskParametersAssert) HasDefaultClientResultChunkSizeValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientResultChunkSize) +} + +func (t *TaskParametersAssert) HasDefaultClientResultColumnCaseInsensitiveValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientResultColumnCaseInsensitive) +} + +func (t *TaskParametersAssert) HasDefaultClientSessionKeepAliveValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientSessionKeepAlive) +} + +func (t *TaskParametersAssert) HasDefaultClientSessionKeepAliveHeartbeatFrequencyValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientSessionKeepAliveHeartbeatFrequency) +} + +func (t *TaskParametersAssert) HasDefaultClientTimestampTypeMappingValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterClientTimestampTypeMapping) +} + +func (t *TaskParametersAssert) HasDefaultDateInputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterDateInputFormat) +} + +func (t *TaskParametersAssert) HasDefaultDateOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterDateOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultEnableUnloadPhysicalTypeOptimizationValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterEnableUnloadPhysicalTypeOptimization) +} + +func (t *TaskParametersAssert) HasDefaultErrorOnNondeterministicMergeValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterErrorOnNondeterministicMerge) +} + +func (t *TaskParametersAssert) HasDefaultErrorOnNondeterministicUpdateValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterErrorOnNondeterministicUpdate) +} + +func (t *TaskParametersAssert) HasDefaultGeographyOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterGeographyOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultGeometryOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterGeometryOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultJdbcTreatTimestampNtzAsUtcValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterJdbcTreatTimestampNtzAsUtc) +} + +func (t *TaskParametersAssert) HasDefaultJdbcUseSessionTimezoneValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterJdbcUseSessionTimezone) +} + +func (t *TaskParametersAssert) HasDefaultJsonIndentValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterJsonIndent) +} + +func (t *TaskParametersAssert) HasDefaultLockTimeoutValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterLockTimeout) +} + +func (t *TaskParametersAssert) HasDefaultLogLevelValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterLogLevel) +} + +func (t *TaskParametersAssert) HasDefaultMultiStatementCountValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterMultiStatementCount) +} + +func (t *TaskParametersAssert) HasDefaultNoorderSequenceAsDefaultValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterNoorderSequenceAsDefault) +} + +func (t *TaskParametersAssert) HasDefaultOdbcTreatDecimalAsIntValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterOdbcTreatDecimalAsInt) +} + +func (t *TaskParametersAssert) HasDefaultQueryTagValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterQueryTag) +} + +func (t *TaskParametersAssert) HasDefaultQuotedIdentifiersIgnoreCaseValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterQuotedIdentifiersIgnoreCase) +} + +func (t *TaskParametersAssert) HasDefaultRowsPerResultsetValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterRowsPerResultset) +} + +func (t *TaskParametersAssert) HasDefaultS3StageVpceDnsNameValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterS3StageVpceDnsName) +} + +func (t *TaskParametersAssert) HasDefaultSearchPathValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterSearchPath) +} + +func (t *TaskParametersAssert) HasDefaultStatementQueuedTimeoutInSecondsValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterStatementQueuedTimeoutInSeconds) +} + +func (t *TaskParametersAssert) HasDefaultStatementTimeoutInSecondsValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterStatementTimeoutInSeconds) +} + +func (t *TaskParametersAssert) HasDefaultStrictJsonOutputValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterStrictJsonOutput) +} + +func (t *TaskParametersAssert) HasDefaultTimestampDayIsAlways24hValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampDayIsAlways24h) +} + +func (t *TaskParametersAssert) HasDefaultTimestampInputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampInputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTimestampLtzOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampLtzOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTimestampNtzOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampNtzOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTimestampOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTimestampTypeMappingValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampTypeMapping) +} + +func (t *TaskParametersAssert) HasDefaultTimestampTzOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimestampTzOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTimezoneValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimezone) +} + +func (t *TaskParametersAssert) HasDefaultTimeInputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimeInputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTimeOutputFormatValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTimeOutputFormat) +} + +func (t *TaskParametersAssert) HasDefaultTraceLevelValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTraceLevel) +} + +func (t *TaskParametersAssert) HasDefaultTransactionAbortOnErrorValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTransactionAbortOnError) +} + +func (t *TaskParametersAssert) HasDefaultTransactionDefaultIsolationLevelValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTransactionDefaultIsolationLevel) +} + +func (t *TaskParametersAssert) HasDefaultTwoDigitCenturyStartValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterTwoDigitCenturyStart) +} + +func (t *TaskParametersAssert) HasDefaultUnsupportedDdlActionValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterUnsupportedDdlAction) +} + +func (t *TaskParametersAssert) HasDefaultUserTaskManagedInitialWarehouseSizeValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterUserTaskManagedInitialWarehouseSize) +} + +func (t *TaskParametersAssert) HasDefaultUseCachedResultValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterUseCachedResult) +} + +func (t *TaskParametersAssert) HasDefaultWeekOfYearPolicyValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterWeekOfYearPolicy) +} + +func (t *TaskParametersAssert) HasDefaultWeekStartValue() *TaskParametersAssert { + return t.HasDefaultParameterValue(sdk.TaskParameterWeekStart) +} + +///////////////////////////////////////////// +// Parameter explicit default value checks // +///////////////////////////////////////////// + +func (t *TaskParametersAssert) HasDefaultAutocommitValueExplicit() *TaskParametersAssert { + return t.HasAutocommit(true) +} + +func (t *TaskParametersAssert) HasDefaultBinaryInputFormatValueExplicit() *TaskParametersAssert { + return t.HasBinaryInputFormat(sdk.BinaryInputFormatHex) +} + +func (t *TaskParametersAssert) HasDefaultBinaryOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasBinaryOutputFormat(sdk.BinaryOutputFormatHex) +} + +func (t *TaskParametersAssert) HasDefaultClientMemoryLimitValueExplicit() *TaskParametersAssert { + return t.HasClientMemoryLimit(1536) +} + +func (t *TaskParametersAssert) HasDefaultClientMetadataRequestUseConnectionCtxValueExplicit() *TaskParametersAssert { + return t.HasClientMetadataRequestUseConnectionCtx(false) +} + +func (t *TaskParametersAssert) HasDefaultClientPrefetchThreadsValueExplicit() *TaskParametersAssert { + return t.HasClientPrefetchThreads(4) +} + +func (t *TaskParametersAssert) HasDefaultClientResultChunkSizeValueExplicit() *TaskParametersAssert { + return t.HasClientResultChunkSize(160) +} + +func (t *TaskParametersAssert) HasDefaultClientResultColumnCaseInsensitiveValueExplicit() *TaskParametersAssert { + return t.HasClientResultColumnCaseInsensitive(false) +} + +func (t *TaskParametersAssert) HasDefaultClientSessionKeepAliveValueExplicit() *TaskParametersAssert { + return t.HasClientSessionKeepAlive(false) +} + +func (t *TaskParametersAssert) HasDefaultClientSessionKeepAliveHeartbeatFrequencyValueExplicit() *TaskParametersAssert { + return t.HasClientSessionKeepAliveHeartbeatFrequency(3600) +} + +func (t *TaskParametersAssert) HasDefaultClientTimestampTypeMappingValueExplicit() *TaskParametersAssert { + return t.HasClientTimestampTypeMapping(sdk.ClientTimestampTypeMappingLtz) +} + +func (t *TaskParametersAssert) HasDefaultDateInputFormatValueExplicit() *TaskParametersAssert { + return t.HasDateInputFormat("AUTO") +} + +func (t *TaskParametersAssert) HasDefaultDateOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasDateOutputFormat("YYYY-MM-DD") +} + +func (t *TaskParametersAssert) HasDefaultEnableUnloadPhysicalTypeOptimizationValueExplicit() *TaskParametersAssert { + return t.HasEnableUnloadPhysicalTypeOptimization(true) +} + +func (t *TaskParametersAssert) HasDefaultErrorOnNondeterministicMergeValueExplicit() *TaskParametersAssert { + return t.HasErrorOnNondeterministicMerge(true) +} + +func (t *TaskParametersAssert) HasDefaultErrorOnNondeterministicUpdateValueExplicit() *TaskParametersAssert { + return t.HasErrorOnNondeterministicUpdate(false) +} + +func (t *TaskParametersAssert) HasDefaultGeographyOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasGeographyOutputFormat(sdk.GeographyOutputFormatGeoJSON) +} + +func (t *TaskParametersAssert) HasDefaultGeometryOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasGeometryOutputFormat(sdk.GeometryOutputFormatGeoJSON) +} + +func (t *TaskParametersAssert) HasDefaultJdbcTreatTimestampNtzAsUtcValueExplicit() *TaskParametersAssert { + return t.HasJdbcTreatTimestampNtzAsUtc(false) +} + +func (t *TaskParametersAssert) HasDefaultJdbcUseSessionTimezoneValueExplicit() *TaskParametersAssert { + return t.HasJdbcUseSessionTimezone(true) +} + +func (t *TaskParametersAssert) HasDefaultJsonIndentValueExplicit() *TaskParametersAssert { + return t.HasJsonIndent(2) +} + +func (t *TaskParametersAssert) HasDefaultLockTimeoutValueExplicit() *TaskParametersAssert { + return t.HasLockTimeout(43200) +} + +func (t *TaskParametersAssert) HasDefaultLogLevelValueExplicit() *TaskParametersAssert { + return t.HasLogLevel(sdk.LogLevelOff) +} + +func (t *TaskParametersAssert) HasDefaultMultiStatementCountValueExplicit() *TaskParametersAssert { + return t.HasMultiStatementCount(1) +} + +func (t *TaskParametersAssert) HasDefaultNoorderSequenceAsDefaultValueExplicit() *TaskParametersAssert { + return t.HasNoorderSequenceAsDefault(true) +} + +func (t *TaskParametersAssert) HasDefaultOdbcTreatDecimalAsIntValueExplicit() *TaskParametersAssert { + return t.HasOdbcTreatDecimalAsInt(false) +} + +func (t *TaskParametersAssert) HasDefaultQueryTagValueExplicit() *TaskParametersAssert { + return t.HasQueryTag("") +} + +func (t *TaskParametersAssert) HasDefaultQuotedIdentifiersIgnoreCaseValueExplicit() *TaskParametersAssert { + return t.HasQuotedIdentifiersIgnoreCase(false) +} + +func (t *TaskParametersAssert) HasDefaultRowsPerResultsetValueExplicit() *TaskParametersAssert { + return t.HasRowsPerResultset(0) +} + +func (t *TaskParametersAssert) HasDefaultS3StageVpceDnsNameValueExplicit() *TaskParametersAssert { + return t.HasS3StageVpceDnsName("") +} + +func (t *TaskParametersAssert) HasDefaultSearchPathValueExplicit() *TaskParametersAssert { + return t.HasSearchPath("$current, $public") +} + +func (t *TaskParametersAssert) HasDefaultStatementQueuedTimeoutInSecondsValueExplicit() *TaskParametersAssert { + return t.HasStatementQueuedTimeoutInSeconds(0) +} + +func (t *TaskParametersAssert) HasDefaultStatementTimeoutInSecondsValueExplicit() *TaskParametersAssert { + return t.HasStatementTimeoutInSeconds(172800) +} + +func (t *TaskParametersAssert) HasDefaultStrictJsonOutputValueExplicit() *TaskParametersAssert { + return t.HasStrictJsonOutput(false) +} + +func (t *TaskParametersAssert) HasDefaultTimestampDayIsAlways24hValueExplicit() *TaskParametersAssert { + return t.HasTimestampDayIsAlways24h(false) +} + +func (t *TaskParametersAssert) HasDefaultTimestampInputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimestampInputFormat("AUTO") +} + +func (t *TaskParametersAssert) HasDefaultTimestampLtzOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimestampLtzOutputFormat("") +} + +func (t *TaskParametersAssert) HasDefaultTimestampNtzOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimestampNtzOutputFormat("YYYY-MM-DD HH24:MI:SS.FF3") +} + +func (t *TaskParametersAssert) HasDefaultTimestampOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimestampOutputFormat("YYYY-MM-DD HH24:MI:SS.FF3 TZHTZM") +} + +func (t *TaskParametersAssert) HasDefaultTimestampTypeMappingValueExplicit() *TaskParametersAssert { + return t.HasTimestampTypeMapping(sdk.TimestampTypeMappingNtz) +} + +func (t *TaskParametersAssert) HasDefaultTimestampTzOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimestampTzOutputFormat("") +} + +func (t *TaskParametersAssert) HasDefaultTimezoneValueExplicit() *TaskParametersAssert { + return t.HasTimezone("America/Los_Angeles") +} + +func (t *TaskParametersAssert) HasDefaultTimeInputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimeInputFormat("AUTO") +} + +func (t *TaskParametersAssert) HasDefaultTimeOutputFormatValueExplicit() *TaskParametersAssert { + return t.HasTimeOutputFormat("HH24:MI:SS") +} + +func (t *TaskParametersAssert) HasDefaultTraceLevelValueExplicit() *TaskParametersAssert { + return t.HasTraceLevel(sdk.TraceLevelOff) +} + +func (t *TaskParametersAssert) HasDefaultTransactionAbortOnErrorValueExplicit() *TaskParametersAssert { + return t.HasTransactionAbortOnError(false) +} + +func (t *TaskParametersAssert) HasDefaultTransactionDefaultIsolationLevelValueExplicit() *TaskParametersAssert { + return t.HasTransactionDefaultIsolationLevel(sdk.TransactionDefaultIsolationLevelReadCommitted) +} + +func (t *TaskParametersAssert) HasDefaultTwoDigitCenturyStartValueExplicit() *TaskParametersAssert { + return t.HasTwoDigitCenturyStart(1970) +} + +func (t *TaskParametersAssert) HasDefaultUnsupportedDdlActionValueExplicit() *TaskParametersAssert { + return t.HasUnsupportedDdlAction(sdk.UnsupportedDDLAction(strings.ToLower(string(sdk.UnsupportedDDLActionIgnore)))) +} + +func (t *TaskParametersAssert) HasDefaultUserTaskManagedInitialWarehouseSizeValueExplicit() *TaskParametersAssert { + return t.HasUserTaskManagedInitialWarehouseSize("Medium") +} + +func (t *TaskParametersAssert) HasDefaultUseCachedResultValueExplicit() *TaskParametersAssert { + return t.HasUseCachedResult(true) +} + +func (t *TaskParametersAssert) HasDefaultWeekOfYearPolicyValueExplicit() *TaskParametersAssert { + return t.HasWeekOfYearPolicy(0) +} + +func (t *TaskParametersAssert) HasDefaultWeekStartValueExplicit() *TaskParametersAssert { + return t.HasWeekStart(0) +} diff --git a/pkg/acceptance/helpers/parameter_client.go b/pkg/acceptance/helpers/parameter_client.go index 3a138fe5ba..70321379b1 100644 --- a/pkg/acceptance/helpers/parameter_client.go +++ b/pkg/acceptance/helpers/parameter_client.go @@ -80,6 +80,17 @@ func (c *ParameterClient) ShowUserParameters(t *testing.T, id sdk.AccountObjectI return params } +func (c *ParameterClient) ShowTaskParameters(t *testing.T, id sdk.SchemaObjectIdentifier) []*sdk.Parameter { + t.Helper() + params, err := c.client().ShowParameters(context.Background(), &sdk.ShowParametersOptions{ + In: &sdk.ParametersIn{ + Task: id, + }, + }) + require.NoError(t, err) + return params +} + func (c *ParameterClient) UpdateAccountParameterTemporarily(t *testing.T, parameter sdk.AccountParameter, newValue string) func() { t.Helper() ctx := context.Background() diff --git a/pkg/acceptance/helpers/task_client.go b/pkg/acceptance/helpers/task_client.go index 233de4297f..17ed53d736 100644 --- a/pkg/acceptance/helpers/task_client.go +++ b/pkg/acceptance/helpers/task_client.go @@ -27,21 +27,21 @@ func (c *TaskClient) client() sdk.Tasks { func (c *TaskClient) defaultCreateTaskRequest(t *testing.T) *sdk.CreateTaskRequest { t.Helper() id := c.ids.RandomSchemaObjectIdentifier() - warehouseReq := sdk.NewCreateTaskWarehouseRequest().WithWarehouse(sdk.Pointer(c.ids.WarehouseId())) - return sdk.NewCreateTaskRequest(id, "SELECT CURRENT_TIMESTAMP").WithWarehouse(warehouseReq) + warehouseReq := sdk.NewCreateTaskWarehouseRequest().WithWarehouse(c.ids.WarehouseId()) + return sdk.NewCreateTaskRequest(id, "SELECT CURRENT_TIMESTAMP").WithWarehouse(*warehouseReq) } -func (c *TaskClient) CreateTask(t *testing.T) (*sdk.Task, func()) { +func (c *TaskClient) Create(t *testing.T) (*sdk.Task, func()) { t.Helper() - return c.CreateTaskWithRequest(t, c.defaultCreateTaskRequest(t).WithSchedule(sdk.String("60 minutes"))) + return c.CreateWithRequest(t, c.defaultCreateTaskRequest(t)) } -func (c *TaskClient) CreateTaskWithAfter(t *testing.T, taskId sdk.SchemaObjectIdentifier) (*sdk.Task, func()) { +func (c *TaskClient) CreateWithAfter(t *testing.T, after ...sdk.SchemaObjectIdentifier) (*sdk.Task, func()) { t.Helper() - return c.CreateTaskWithRequest(t, c.defaultCreateTaskRequest(t).WithAfter([]sdk.SchemaObjectIdentifier{taskId})) + return c.CreateWithRequest(t, c.defaultCreateTaskRequest(t).WithAfter(after)) } -func (c *TaskClient) CreateTaskWithRequest(t *testing.T, request *sdk.CreateTaskRequest) (*sdk.Task, func()) { +func (c *TaskClient) CreateWithRequest(t *testing.T, request *sdk.CreateTaskRequest) (*sdk.Task, func()) { t.Helper() ctx := context.Background() @@ -53,15 +53,22 @@ func (c *TaskClient) CreateTaskWithRequest(t *testing.T, request *sdk.CreateTask task, err := c.client().ShowByID(ctx, id) require.NoError(t, err) - return task, c.DropTaskFunc(t, id) + return task, c.DropFunc(t, id) } -func (c *TaskClient) DropTaskFunc(t *testing.T, id sdk.SchemaObjectIdentifier) func() { +func (c *TaskClient) DropFunc(t *testing.T, id sdk.SchemaObjectIdentifier) func() { t.Helper() ctx := context.Background() return func() { - err := c.client().Drop(ctx, sdk.NewDropTaskRequest(id).WithIfExists(sdk.Bool(true))) + err := c.client().Drop(ctx, sdk.NewDropTaskRequest(id).WithIfExists(true)) require.NoError(t, err) } } + +func (c *TaskClient) Show(t *testing.T, id sdk.SchemaObjectIdentifier) (*sdk.Task, error) { + t.Helper() + ctx := context.Background() + + return c.client().ShowByID(ctx, id) +} diff --git a/pkg/datasources/tasks.go b/pkg/datasources/tasks.go index 2ab4bed27e..5af820fa7c 100644 --- a/pkg/datasources/tasks.go +++ b/pkg/datasources/tasks.go @@ -69,7 +69,7 @@ func ReadTasks(d *schema.ResourceData, meta interface{}) error { databaseName := d.Get("database").(string) schemaName := d.Get("schema").(string) - extractedTasks, err := client.Tasks.Show(ctx, sdk.NewShowTaskRequest().WithIn(&sdk.In{Schema: sdk.NewDatabaseObjectIdentifier(databaseName, schemaName)})) + extractedTasks, err := client.Tasks.Show(ctx, sdk.NewShowTaskRequest().WithIn(sdk.In{Schema: sdk.NewDatabaseObjectIdentifier(databaseName, schemaName)})) if err != nil { // If not found, mark resource to be removed from state file during apply or refresh log.Printf("[DEBUG] tasks in schema (%s) not found", d.Id()) diff --git a/pkg/resources/resource_monitor_acceptance_test.go b/pkg/resources/resource_monitor_acceptance_test.go index 304112d60c..0f7a02322a 100644 --- a/pkg/resources/resource_monitor_acceptance_test.go +++ b/pkg/resources/resource_monitor_acceptance_test.go @@ -771,11 +771,15 @@ func TestAcc_ResourceMonitor_Issue1500_AlteringWithOnlyTriggers(t *testing.T) { ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, Config: config.FromModel(t, configModelWithUpdatedTriggers), }, - // Update only triggers (not allowed in Snowflake) + // Update only triggers (not allowed in Snowflake; recreating) { + ConfigPlanChecks: resource.ConfigPlanChecks{ + PreApply: []plancheck.PlanCheck{ + plancheck.ExpectResourceAction("snowflake_resource_monitor.test", plancheck.ResourceActionDestroyBeforeCreate), + }, + }, ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories, Config: config.FromModel(t, configModelWithoutTriggers), - ExpectError: regexp.MustCompile("Due to Snowflake limitations triggers cannot be completely removed form"), }, }, }) diff --git a/pkg/resources/task.go b/pkg/resources/task.go index 8a135be2c3..078e29686d 100644 --- a/pkg/resources/task.go +++ b/pkg/resources/task.go @@ -182,7 +182,7 @@ func ReadTask(d *schema.ResourceData, meta interface{}) error { return err } - if err := d.Set("enabled", task.IsStarted()); err != nil { + if err := d.Set("enabled", task.State == sdk.TaskStateStarted); err != nil { return err } @@ -305,7 +305,7 @@ func CreateTask(d *schema.ResourceData, meta interface{}) error { // Set optionals if v, ok := d.GetOk("warehouse"); ok { warehouseId := sdk.NewAccountObjectIdentifier(v.(string)) - createRequest.WithWarehouse(sdk.NewCreateTaskWarehouseRequest().WithWarehouse(&warehouseId)) + createRequest.WithWarehouse(*sdk.NewCreateTaskWarehouseRequest().WithWarehouse(warehouseId)) } if v, ok := d.GetOk("user_task_managed_initial_warehouse_size"); ok { @@ -313,11 +313,11 @@ func CreateTask(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - createRequest.WithWarehouse(sdk.NewCreateTaskWarehouseRequest().WithUserTaskManagedInitialWarehouseSize(&size)) + createRequest.WithWarehouse(*sdk.NewCreateTaskWarehouseRequest().WithUserTaskManagedInitialWarehouseSize(size)) } if v, ok := d.GetOk("schedule"); ok { - createRequest.WithSchedule(sdk.String(v.(string))) + createRequest.WithSchedule(v.(string)) } if v, ok := d.GetOk("session_parameters"); ok { @@ -325,27 +325,31 @@ func CreateTask(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - createRequest.WithSessionParameters(sessionParameters) + createRequest.WithSessionParameters(*sessionParameters) } if v, ok := d.GetOk("user_task_timeout_ms"); ok { - createRequest.WithUserTaskTimeoutMs(sdk.Int(v.(int))) + createRequest.WithUserTaskTimeoutMs(v.(int)) } if v, ok := d.GetOk("suspend_task_after_num_failures"); ok { - createRequest.WithSuspendTaskAfterNumFailures(sdk.Int(v.(int))) + createRequest.WithSuspendTaskAfterNumFailures(v.(int)) } if v, ok := d.GetOk("comment"); ok { - createRequest.WithComment(sdk.String(v.(string))) + createRequest.WithComment(v.(string)) } if v, ok := d.GetOk("allow_overlapping_execution"); ok { - createRequest.WithAllowOverlappingExecution(sdk.Bool(v.(bool))) + createRequest.WithAllowOverlappingExecution(v.(bool)) } if v, ok := d.GetOk("error_integration"); ok { - createRequest.WithErrorIntegration(sdk.String(v.(string))) + errorIntegrationId, err := sdk.ParseAccountObjectIdentifier(v.(string)) + if err != nil { + return err + } + createRequest.WithErrorNotificationIntegration(errorIntegrationId) } if v, ok := d.GetOk("after"); ok { @@ -369,7 +373,7 @@ func CreateTask(d *schema.ResourceData, meta interface{}) error { } if v, ok := d.GetOk("when"); ok { - createRequest.WithWhen(sdk.String(v.(string))) + createRequest.WithWhen(v.(string)) } if err := client.Tasks.Create(ctx, createRequest); err != nil { @@ -389,7 +393,7 @@ func CreateTask(d *schema.ResourceData, meta interface{}) error { } func waitForTaskStart(ctx context.Context, client *sdk.Client, id sdk.SchemaObjectIdentifier) error { - err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(id).WithResume(sdk.Bool(true))) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(id).WithResume(true)) if err != nil { return fmt.Errorf("error starting task %s err = %w", id.FullyQualifiedName(), err) } @@ -398,7 +402,7 @@ func waitForTaskStart(ctx context.Context, client *sdk.Client, id sdk.SchemaObje if err != nil { return fmt.Errorf("error starting task %s err = %w", id.FullyQualifiedName(), err), false } - if !task.IsStarted() { + if task.State != sdk.TaskStateStarted { return nil, false } return nil, true @@ -426,9 +430,9 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { newWarehouse := d.Get("warehouse") alterRequest := sdk.NewAlterTaskRequest(taskId) if newWarehouse == "" { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithWarehouse(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithWarehouse(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithWarehouse(sdk.Pointer(sdk.NewAccountObjectIdentifier(newWarehouse.(string))))) + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithWarehouse(sdk.NewAccountObjectIdentifier(newWarehouse.(string)))) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -445,7 +449,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - alterRequest := sdk.NewAlterTaskRequest(taskId).WithSet(sdk.NewTaskSetRequest().WithUserTaskManagedInitialWarehouseSize(&size)) + alterRequest := sdk.NewAlterTaskRequest(taskId).WithSet(*sdk.NewTaskSetRequest().WithUserTaskManagedInitialWarehouseSize(size)) err = client.Tasks.Alter(ctx, alterRequest) if err != nil { return fmt.Errorf("error updating user_task_managed_initial_warehouse_size on task %s", taskId.FullyQualifiedName()) @@ -457,9 +461,13 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { newErrorIntegration := d.Get("error_integration") alterRequest := sdk.NewAlterTaskRequest(taskId) if newErrorIntegration == "" { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithErrorIntegration(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithErrorIntegration(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithErrorIntegration(sdk.String(newErrorIntegration.(string)))) + newErrorIntegrationId, err := sdk.ParseAccountObjectIdentifier(newErrorIntegration.(string)) + if err != nil { + return err + } + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithErrorNotificationIntegration(newErrorIntegrationId)) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -470,7 +478,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if d.HasChange("after") { // making changes to after require suspending the current task // (the task will be brought up to the correct running state in the "enabled" check at the bottom of Update function). - err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSuspend(sdk.Bool(true))) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSuspend(true)) if err != nil { return fmt.Errorf("error suspending task %s, err: %w", taskId.FullyQualifiedName(), err) } @@ -481,7 +489,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if len(newAfter) > 0 { // preemptively removing schedule because a task cannot have both after and schedule - if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithUnset(sdk.NewTaskUnsetRequest().WithSchedule(sdk.Bool(true)))); err != nil { + if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithUnset(*sdk.NewTaskUnsetRequest().WithSchedule(true))); err != nil { return fmt.Errorf("error updating schedule on task %s", taskId.FullyQualifiedName()) } } @@ -529,9 +537,9 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { newSchedule := d.Get("schedule") alterRequest := sdk.NewAlterTaskRequest(taskId) if newSchedule == "" { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithSchedule(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithSchedule(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithSchedule(sdk.String(newSchedule.(string)))) + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithSchedule(newSchedule.(string))) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -543,9 +551,9 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("user_task_timeout_ms") alterRequest := sdk.NewAlterTaskRequest(taskId) if o.(int) > 0 && n.(int) == 0 { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithUserTaskTimeoutMs(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithUserTaskTimeoutMs(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithUserTaskTimeoutMs(sdk.Int(n.(int)))) + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithUserTaskTimeoutMs(n.(int))) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -557,9 +565,9 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { o, n := d.GetChange("suspend_task_after_num_failures") alterRequest := sdk.NewAlterTaskRequest(taskId) if o.(int) > 0 && n.(int) == 0 { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithSuspendTaskAfterNumFailures(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithSuspendTaskAfterNumFailures(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithSuspendTaskAfterNumFailures(sdk.Int(n.(int)))) + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithSuspendTaskAfterNumFailures(n.(int))) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -571,9 +579,9 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { newComment := d.Get("comment") alterRequest := sdk.NewAlterTaskRequest(taskId) if newComment == "" { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithComment(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithComment(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithComment(sdk.String(newComment.(string)))) + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithComment(newComment.(string))) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -585,9 +593,9 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { n := d.Get("allow_overlapping_execution") alterRequest := sdk.NewAlterTaskRequest(taskId) if n == "" { - alterRequest.WithUnset(sdk.NewTaskUnsetRequest().WithAllowOverlappingExecution(sdk.Bool(true))) + alterRequest.WithUnset(*sdk.NewTaskUnsetRequest().WithAllowOverlappingExecution(true)) } else { - alterRequest.WithSet(sdk.NewTaskSetRequest().WithAllowOverlappingExecution(sdk.Bool(n.(bool)))) + alterRequest.WithSet(*sdk.NewTaskSetRequest().WithAllowOverlappingExecution(n.(bool))) } err := client.Tasks.Alter(ctx, alterRequest) if err != nil { @@ -616,7 +624,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithUnset(sdk.NewTaskUnsetRequest().WithSessionParametersUnset(sessionParametersUnset))); err != nil { + if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithUnset(*sdk.NewTaskUnsetRequest().WithSessionParametersUnset(*sessionParametersUnset))); err != nil { return fmt.Errorf("error removing session_parameters on task %v err = %w", d.Id(), err) } } @@ -626,7 +634,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSet(sdk.NewTaskSetRequest().WithSessionParameters(sessionParameters))); err != nil { + if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSet(*sdk.NewTaskSetRequest().WithSessionParameters(*sessionParameters))); err != nil { return fmt.Errorf("error adding session_parameters to task %v err = %w", d.Id(), err) } } @@ -636,7 +644,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if err != nil { return err } - if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSet(sdk.NewTaskSetRequest().WithSessionParameters(sessionParameters))); err != nil { + if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSet(*sdk.NewTaskSetRequest().WithSessionParameters(*sessionParameters))); err != nil { return fmt.Errorf("error updating session_parameters in task %v err = %w", d.Id(), err) } } @@ -644,7 +652,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if d.HasChange("when") { n := d.Get("when") - alterRequest := sdk.NewAlterTaskRequest(taskId).WithModifyWhen(sdk.String(n.(string))) + alterRequest := sdk.NewAlterTaskRequest(taskId).WithModifyWhen(n.(string)) err := client.Tasks.Alter(ctx, alterRequest) if err != nil { return fmt.Errorf("error updating when condition on task %s", taskId.FullyQualifiedName()) @@ -653,7 +661,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { if d.HasChange("sql_statement") { n := d.Get("sql_statement") - alterRequest := sdk.NewAlterTaskRequest(taskId).WithModifyAs(sdk.String(n.(string))) + alterRequest := sdk.NewAlterTaskRequest(taskId).WithModifyAs(n.(string)) err := client.Tasks.Alter(ctx, alterRequest) if err != nil { return fmt.Errorf("error updating sql statement on task %s", taskId.FullyQualifiedName()) @@ -666,7 +674,7 @@ func UpdateTask(d *schema.ResourceData, meta interface{}) error { log.Printf("[WARN] failed to resume task %s", taskId.FullyQualifiedName()) } } else { - if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSuspend(sdk.Bool(true))); err != nil { + if err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(taskId).WithSuspend(true)); err != nil { return fmt.Errorf("failed to suspend task %s", taskId.FullyQualifiedName()) } } diff --git a/pkg/sdk/grants_impl.go b/pkg/sdk/grants_impl.go index b64c83b0e5..d0399d605b 100644 --- a/pkg/sdk/grants_impl.go +++ b/pkg/sdk/grants_impl.go @@ -503,14 +503,14 @@ func (v *grants) runOnAllPipes(ctx context.Context, inDatabase *AccountObjectIde } func (v *grants) runOnAllTasks(ctx context.Context, inDatabase *AccountObjectIdentifier, inSchema *DatabaseObjectIdentifier, command func(Task) error) error { - var in *In + var in In switch { case inDatabase != nil: - in = &In{ + in = In{ Database: *inDatabase, } case inSchema != nil: - in = &In{ + in = In{ Schema: *inSchema, } } diff --git a/pkg/sdk/parameters.go b/pkg/sdk/parameters.go index 79445c3eae..763cd7668c 100644 --- a/pkg/sdk/parameters.go +++ b/pkg/sdk/parameters.go @@ -654,6 +654,71 @@ var AllUserParameters = []UserParameter{ UserParameterPreventUnloadToInternalStages, } +type TaskParameter string + +// TODO(SNOW-1348116 - next prs): Handle task parameters +const ( + // Task Parameters + TaskParameterUserTaskManagedInitialWarehouseSize TaskParameter = "USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE" + + // Session Parameters (inherited) + TaskParameterAbortDetachedQuery TaskParameter = "ABORT_DETACHED_QUERY" + TaskParameterAutocommit TaskParameter = "AUTOCOMMIT" + TaskParameterBinaryInputFormat TaskParameter = "BINARY_INPUT_FORMAT" + TaskParameterBinaryOutputFormat TaskParameter = "BINARY_OUTPUT_FORMAT" + TaskParameterClientMemoryLimit TaskParameter = "CLIENT_MEMORY_LIMIT" + TaskParameterClientMetadataRequestUseConnectionCtx TaskParameter = "CLIENT_METADATA_REQUEST_USE_CONNECTION_CTX" + TaskParameterClientPrefetchThreads TaskParameter = "CLIENT_PREFETCH_THREADS" + TaskParameterClientResultChunkSize TaskParameter = "CLIENT_RESULT_CHUNK_SIZE" + TaskParameterClientResultColumnCaseInsensitive TaskParameter = "CLIENT_RESULT_COLUMN_CASE_INSENSITIVE" + TaskParameterClientSessionKeepAlive TaskParameter = "CLIENT_SESSION_KEEP_ALIVE" + TaskParameterClientSessionKeepAliveHeartbeatFrequency TaskParameter = "CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY" + TaskParameterClientTimestampTypeMapping TaskParameter = "CLIENT_TIMESTAMP_TYPE_MAPPING" + TaskParameterDateInputFormat TaskParameter = "DATE_INPUT_FORMAT" + TaskParameterDateOutputFormat TaskParameter = "DATE_OUTPUT_FORMAT" + TaskParameterEnableUnloadPhysicalTypeOptimization TaskParameter = "ENABLE_UNLOAD_PHYSICAL_TYPE_OPTIMIZATION" + TaskParameterErrorOnNondeterministicMerge TaskParameter = "ERROR_ON_NONDETERMINISTIC_MERGE" + TaskParameterErrorOnNondeterministicUpdate TaskParameter = "ERROR_ON_NONDETERMINISTIC_UPDATE" + TaskParameterGeographyOutputFormat TaskParameter = "GEOGRAPHY_OUTPUT_FORMAT" + TaskParameterGeometryOutputFormat TaskParameter = "GEOMETRY_OUTPUT_FORMAT" + TaskParameterJdbcTreatDecimalAsInt TaskParameter = "JDBC_TREAT_DECIMAL_AS_INT" + TaskParameterJdbcTreatTimestampNtzAsUtc TaskParameter = "JDBC_TREAT_TIMESTAMP_NTZ_AS_UTC" + TaskParameterJdbcUseSessionTimezone TaskParameter = "JDBC_USE_SESSION_TIMEZONE" + TaskParameterJsonIndent TaskParameter = "JSON_INDENT" + TaskParameterLockTimeout TaskParameter = "LOCK_TIMEOUT" + TaskParameterLogLevel TaskParameter = "LOG_LEVEL" + TaskParameterMultiStatementCount TaskParameter = "MULTI_STATEMENT_COUNT" + TaskParameterNoorderSequenceAsDefault TaskParameter = "NOORDER_SEQUENCE_AS_DEFAULT" + TaskParameterOdbcTreatDecimalAsInt TaskParameter = "ODBC_TREAT_DECIMAL_AS_INT" + TaskParameterQueryTag TaskParameter = "QUERY_TAG" + TaskParameterQuotedIdentifiersIgnoreCase TaskParameter = "QUOTED_IDENTIFIERS_IGNORE_CASE" + TaskParameterRowsPerResultset TaskParameter = "ROWS_PER_RESULTSET" + TaskParameterS3StageVpceDnsName TaskParameter = "S3_STAGE_VPCE_DNS_NAME" + TaskParameterSearchPath TaskParameter = "SEARCH_PATH" + TaskParameterSimulatedDataSharingConsumer TaskParameter = "SIMULATED_DATA_SHARING_CONSUMER" + TaskParameterStatementQueuedTimeoutInSeconds TaskParameter = "STATEMENT_QUEUED_TIMEOUT_IN_SECONDS" + TaskParameterStatementTimeoutInSeconds TaskParameter = "STATEMENT_TIMEOUT_IN_SECONDS" + TaskParameterStrictJsonOutput TaskParameter = "STRICT_JSON_OUTPUT" + TaskParameterTimestampDayIsAlways24h TaskParameter = "TIMESTAMP_DAY_IS_ALWAYS_24H" + TaskParameterTimestampInputFormat TaskParameter = "TIMESTAMP_INPUT_FORMAT" + TaskParameterTimestampLtzOutputFormat TaskParameter = "TIMESTAMP_LTZ_OUTPUT_FORMAT" + TaskParameterTimestampNtzOutputFormat TaskParameter = "TIMESTAMP_NTZ_OUTPUT_FORMAT" + TaskParameterTimestampOutputFormat TaskParameter = "TIMESTAMP_OUTPUT_FORMAT" + TaskParameterTimestampTypeMapping TaskParameter = "TIMESTAMP_TYPE_MAPPING" + TaskParameterTimestampTzOutputFormat TaskParameter = "TIMESTAMP_TZ_OUTPUT_FORMAT" + TaskParameterTimezone TaskParameter = "TIMEZONE" + TaskParameterTimeInputFormat TaskParameter = "TIME_INPUT_FORMAT" + TaskParameterTimeOutputFormat TaskParameter = "TIME_OUTPUT_FORMAT" + TaskParameterTraceLevel TaskParameter = "TRACE_LEVEL" + TaskParameterTransactionAbortOnError TaskParameter = "TRANSACTION_ABORT_ON_ERROR" + TaskParameterTransactionDefaultIsolationLevel TaskParameter = "TRANSACTION_DEFAULT_ISOLATION_LEVEL" + TaskParameterTwoDigitCenturyStart TaskParameter = "TWO_DIGIT_CENTURY_START" + TaskParameterUnsupportedDdlAction TaskParameter = "UNSUPPORTED_DDL_ACTION" + TaskParameterUseCachedResult TaskParameter = "USE_CACHED_RESULT" + TaskParameterWeekOfYearPolicy TaskParameter = "WEEK_OF_YEAR_POLICY" + TaskParameterWeekStart TaskParameter = "WEEK_START" +) + type WarehouseParameter string const ( @@ -1239,6 +1304,7 @@ const ( ParameterTypeWarehouse ParameterType = "WAREHOUSE" ParameterTypeDatabase ParameterType = "DATABASE" ParameterTypeSchema ParameterType = "SCHEMA" + ParameterTypeTask ParameterType = "TASK" ) type Parameter struct { diff --git a/pkg/sdk/poc/generator/static_builders.go b/pkg/sdk/poc/generator/static_builders.go index 2f025e56bb..909ac3361c 100644 --- a/pkg/sdk/poc/generator/static_builders.go +++ b/pkg/sdk/poc/generator/static_builders.go @@ -9,6 +9,10 @@ func (v *QueryStruct) Create() *QueryStruct { return v.SQL("CREATE") } +func (v *QueryStruct) CreateOrAlter() *QueryStruct { + return v.SQL("CREATE OR ALTER") +} + func (v *QueryStruct) Alter() *QueryStruct { return v.SQL("ALTER") } diff --git a/pkg/sdk/poc/generator/validation.go b/pkg/sdk/poc/generator/validation.go index fa664c9bd6..3f0b9eb15f 100644 --- a/pkg/sdk/poc/generator/validation.go +++ b/pkg/sdk/poc/generator/validation.go @@ -2,6 +2,7 @@ package generator import ( "fmt" + "log" "strings" ) @@ -68,7 +69,10 @@ func (v *Validation) Condition(field *Field) string { case ValidateValueSet: return fmt.Sprintf("!valueSet(%s)", strings.Join(v.fieldsWithPath(field), ",")) case ValidateValue: - return fmt.Sprintf("err := %s.validate(); err != nil", strings.Join(v.fieldsWithPath(field.Parent), ",")) + if len(v.FieldNames) != 1 { + log.Panicf("expected ValidateValue to be called exactly one field, got: %v", v.FieldNames) + } + return fmt.Sprintf("err := %s.validate(); err != nil", v.fieldsWithPath(field)[0]) } panic("condition for validation unknown") } diff --git a/pkg/sdk/tasks_def.go b/pkg/sdk/tasks_def.go index 9f1c14fe2d..26214a521d 100644 --- a/pkg/sdk/tasks_def.go +++ b/pkg/sdk/tasks_def.go @@ -1,52 +1,130 @@ package sdk -import g "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk/poc/generator" +import ( + "encoding/json" + "fmt" + "strings" + + g "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk/poc/generator" +) //go:generate go run ./poc/main.go +type TaskState string + +const ( + TaskStateStarted TaskState = "started" + TaskStateSuspended TaskState = "suspended" +) + +func ToTaskState(s string) (TaskState, error) { + switch taskState := TaskState(strings.ToLower(s)); taskState { + case TaskStateStarted, TaskStateSuspended: + return taskState, nil + default: + return "", fmt.Errorf("unknown task state: %s", s) + } +} + +type TaskRelationsRepresentation struct { + Predecessors []string `json:"Predecessors"` + FinalizerTask string `json:"FinalizerTask"` +} + +func (r *TaskRelationsRepresentation) ToTaskRelations() (TaskRelations, error) { + predecessors := make([]SchemaObjectIdentifier, len(r.Predecessors)) + for i, predecessor := range r.Predecessors { + id, err := ParseSchemaObjectIdentifier(predecessor) + if err != nil { + return TaskRelations{}, err + } + predecessors[i] = id + } + + taskRelations := TaskRelations{ + Predecessors: predecessors, + } + + if len(r.FinalizerTask) > 0 { + finalizerTask, err := ParseSchemaObjectIdentifier(r.FinalizerTask) + if err != nil { + return TaskRelations{}, err + } + taskRelations.FinalizerTask = &finalizerTask + } + + return taskRelations, nil +} + +type TaskRelations struct { + Predecessors []SchemaObjectIdentifier + FinalizerTask *SchemaObjectIdentifier +} + +func ToTaskRelations(s string) (TaskRelations, error) { + var taskRelationsRepresentation TaskRelationsRepresentation + if err := json.Unmarshal([]byte(s), &taskRelationsRepresentation); err != nil { + return TaskRelations{}, err + } + taskRelations, err := taskRelationsRepresentation.ToTaskRelations() + if err != nil { + return TaskRelations{}, err + } + return taskRelations, nil +} + var taskDbRow = g.DbStruct("taskDBRow"). - Field("created_on", "string"). - Field("name", "string"). - Field("id", "string"). - Field("database_name", "string"). - Field("schema_name", "string"). - Field("owner", "string"). - Field("comment", "string"). - Field("warehouse", "string"). - Field("schedule", "string"). - Field("predecessors", "string"). - Field("state", "string"). - Field("definition", "string"). - Field("condition", "string"). - Field("allow_overlapping_execution", "string"). - Field("error_integration", "string"). - Field("last_committed_on", "string"). - Field("last_suspended_on", "string"). - Field("owner_role_type", "string"). - Field("config", "string"). - Field("budget", "string") + Text("created_on"). + Text("name"). + Text("id"). + Text("database_name"). + Text("schema_name"). + Text("owner"). + OptionalText("comment"). + OptionalText("warehouse"). + OptionalText("schedule"). + Text("predecessors"). + Text("state"). + Text("definition"). + OptionalText("condition"). + Text("allow_overlapping_execution"). + OptionalText("error_integration"). + OptionalText("last_committed_on"). + OptionalText("last_suspended_on"). + Text("owner_role_type"). + OptionalText("config"). + OptionalText("budget"). + Text("task_relations"). + OptionalText("last_suspended_reason") var task = g.PlainStruct("Task"). - Field("CreatedOn", "string"). - Field("Name", "string"). - Field("Id", "string"). - Field("DatabaseName", "string"). - Field("SchemaName", "string"). - Field("Owner", "string"). - Field("Comment", "string"). - Field("Warehouse", "string"). - Field("Schedule", "string"). - Field("Predecessors", "string"). - Field("State", "string"). - Field("Definition", "string"). - Field("Condition", "string"). - Field("AllowOverlappingExecution", "string"). - Field("ErrorIntegration", "string"). - Field("LastCommittedOn", "string"). - Field("LastSuspendedOn", "string"). - Field("OwnerRoleType", "string"). - Field("Config", "string"). - Field("Budget", "string") + Text("CreatedOn"). + Text("Name"). + Text("Id"). + Text("DatabaseName"). + Text("SchemaName"). + Text("Owner"). + OptionalText("Comment"). + OptionalText("Warehouse"). + OptionalText("Schedule"). + Field("Predecessors", g.KindOfTSlice[SchemaObjectIdentifier]()). + Field("State", g.KindOfT[TaskState]()). + Text("Definition"). + OptionalText("Condition"). + Bool("AllowOverlappingExecution"). + Field("ErrorIntegration", g.KindOfTSlice[AccountObjectIdentifier]()). + OptionalText("LastCommittedOn"). + OptionalText("LastSuspendedOn"). + Text("OwnerRoleType"). + OptionalText("Config"). + OptionalText("Budget"). + Text("TaskRelations"). + OptionalText("LastSuspendedReason") + +var taskCreateWarehouse = g.NewQueryStruct("CreateTaskWarehouse"). + OptionalIdentifier("Warehouse", g.KindOfT[AccountObjectIdentifier](), g.IdentifierOptions().Equals().SQL("WAREHOUSE")). + OptionalAssignment("USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE", "WarehouseSize", g.ParameterOptions().SingleQuotes()). + WithValidation(g.ExactlyOneValueSet, "Warehouse", "UserTaskManagedInitialWarehouseSize") var TasksDef = g.NewInterface( "Tasks", @@ -61,34 +139,56 @@ var TasksDef = g.NewInterface( SQL("TASK"). IfNotExists(). Name(). - OptionalQueryStructField( - "Warehouse", - g.NewQueryStruct("CreateTaskWarehouse"). - OptionalIdentifier("Warehouse", g.KindOfT[AccountObjectIdentifier](), g.IdentifierOptions().Equals().SQL("WAREHOUSE")). - OptionalAssignment("USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE", "WarehouseSize", g.ParameterOptions().SingleQuotes()). - WithValidation(g.ExactlyOneValueSet, "Warehouse", "UserTaskManagedInitialWarehouseSize"), - g.KeywordOptions(), - ). + PredefinedQueryStructField("Warehouse", "*CreateTaskWarehouse", g.KeywordOptions()). OptionalTextAssignment("SCHEDULE", g.ParameterOptions().SingleQuotes()). OptionalTextAssignment("CONFIG", g.ParameterOptions().NoQuotes()). OptionalBooleanAssignment("ALLOW_OVERLAPPING_EXECUTION", nil). OptionalSessionParameters(). OptionalNumberAssignment("USER_TASK_TIMEOUT_MS", nil). OptionalNumberAssignment("SUSPEND_TASK_AFTER_NUM_FAILURES", nil). - OptionalTextAssignment("ERROR_INTEGRATION", g.ParameterOptions().NoQuotes()). - OptionalSQL("COPY GRANTS"). + OptionalIdentifier("ErrorNotificationIntegration", g.KindOfT[AccountObjectIdentifier](), g.IdentifierOptions().Equals().SQL("ERROR_INTEGRATION")). OptionalTextAssignment("COMMENT", g.ParameterOptions().SingleQuotes()). - ListAssignment("AFTER", "SchemaObjectIdentifier", g.ParameterOptions().NoEquals()). + OptionalIdentifier("Finalize", g.KindOfT[SchemaObjectIdentifier](), g.IdentifierOptions().Equals().SQL("FINALIZE")). + OptionalNumberAssignment("TASK_AUTO_RETRY_ATTEMPTS", g.ParameterOptions()). OptionalTags(). + OptionalNumberAssignment("USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS", g.ParameterOptions()). + List("AFTER", g.KindOfT[SchemaObjectIdentifier](), g.ListOptions()). OptionalTextAssignment("WHEN", g.ParameterOptions().NoQuotes().NoEquals()). SQL("AS"). Text("sql", g.KeywordOptions().NoQuotes().Required()). WithValidation(g.ValidIdentifier, "name"). + WithValidation(g.ValidIdentifierIfSet, "ErrorNotificationIntegration"). WithValidation(g.ConflictingFields, "OrReplace", "IfNotExists"), + taskCreateWarehouse, + ). + CustomOperation( + "CreateOrAlter", + "https://docs.snowflake.com/en/sql-reference/sql/create-task#create-or-alter-task", + g.NewQueryStruct("CloneTask"). + CreateOrAlter(). + SQL("TASK"). + Name(). + PredefinedQueryStructField("Warehouse", "*CreateTaskWarehouse", g.KeywordOptions()). + OptionalTextAssignment("SCHEDULE", g.ParameterOptions().SingleQuotes()). + OptionalTextAssignment("CONFIG", g.ParameterOptions().NoQuotes()). + OptionalBooleanAssignment("ALLOW_OVERLAPPING_EXECUTION", nil). + OptionalNumberAssignment("USER_TASK_TIMEOUT_MS", nil). + OptionalSessionParameters(). + OptionalNumberAssignment("SUSPEND_TASK_AFTER_NUM_FAILURES", nil). + OptionalIdentifier("ErrorNotificationIntegration", g.KindOfT[AccountObjectIdentifier](), g.IdentifierOptions().Equals().SQL("ERROR_INTEGRATION")). + OptionalTextAssignment("COMMENT", g.ParameterOptions().SingleQuotes()). + OptionalIdentifier("Finalize", g.KindOfT[SchemaObjectIdentifier](), g.IdentifierOptions().Equals().SQL("FINALIZE")). + OptionalNumberAssignment("TASK_AUTO_RETRY_ATTEMPTS", g.ParameterOptions()). + List("AFTER", g.KindOfT[SchemaObjectIdentifier](), g.ListOptions()). + OptionalTextAssignment("WHEN", g.ParameterOptions().NoQuotes().NoEquals()). + SQL("AS"). + Text("sql", g.KeywordOptions().NoQuotes().Required()). + WithValidation(g.ValidIdentifier, "name"). + WithValidation(g.ValidIdentifierIfSet, "ErrorNotificationIntegration"), ). CustomOperation( "Clone", - "https://docs.snowflake.com/en/sql-reference/sql/create-task#variant-syntax", + "https://docs.snowflake.com/en/sql-reference/sql/create-task#create-task-clone", g.NewQueryStruct("CloneTask"). Create(). OrReplace(). @@ -121,12 +221,15 @@ var TasksDef = g.NewInterface( OptionalBooleanAssignment("ALLOW_OVERLAPPING_EXECUTION", nil). OptionalNumberAssignment("USER_TASK_TIMEOUT_MS", nil). OptionalNumberAssignment("SUSPEND_TASK_AFTER_NUM_FAILURES", nil). - OptionalTextAssignment("ERROR_INTEGRATION", g.ParameterOptions().NoQuotes()). + OptionalIdentifier("ErrorNotificationIntegration", g.KindOfT[AccountObjectIdentifier](), g.IdentifierOptions().Equals().SQL("ERROR_INTEGRATION")). OptionalTextAssignment("COMMENT", g.ParameterOptions().SingleQuotes()). OptionalSessionParameters(). - WithValidation(g.AtLeastOneValueSet, "Warehouse", "UserTaskManagedInitialWarehouseSize", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParameters"). - WithValidation(g.ConflictingFields, "Warehouse", "UserTaskManagedInitialWarehouseSize"), - g.KeywordOptions().SQL("SET"), + OptionalNumberAssignment("TASK_AUTO_RETRY_ATTEMPTS", nil). + OptionalNumberAssignment("USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS", nil). + WithValidation(g.AtLeastOneValueSet, "Warehouse", "UserTaskManagedInitialWarehouseSize", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParameters", "TaskAutoRetryAttempts", "UserTaskMinimumTriggerIntervalInSeconds"). + WithValidation(g.ConflictingFields, "Warehouse", "UserTaskManagedInitialWarehouseSize"). + WithValidation(g.ValidIdentifierIfSet, "ErrorNotificationIntegration"), + g.ListOptions().SQL("SET"), ). OptionalQueryStructField( "Unset", @@ -139,16 +242,21 @@ var TasksDef = g.NewInterface( OptionalSQL("SUSPEND_TASK_AFTER_NUM_FAILURES"). OptionalSQL("ERROR_INTEGRATION"). OptionalSQL("COMMENT"). + OptionalSQL("TASK_AUTO_RETRY_ATTEMPTS"). + OptionalSQL("USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS"). OptionalSessionParametersUnset(). - WithValidation(g.AtLeastOneValueSet, "Warehouse", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParametersUnset"), - g.KeywordOptions().SQL("UNSET"), + WithValidation(g.AtLeastOneValueSet, "Warehouse", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParametersUnset", "TaskAutoRetryAttempts", "UserTaskMinimumTriggerIntervalInSeconds"), + g.ListOptions().SQL("UNSET"), ). OptionalSetTags(). OptionalUnsetTags(). + OptionalIdentifier("SetFinalize", g.KindOfT[SchemaObjectIdentifier](), g.IdentifierOptions().Equals().SQL("SET FINALIZE")). + OptionalSQL("UNSET FINALIZE"). OptionalTextAssignment("MODIFY AS", g.ParameterOptions().NoQuotes().NoEquals()). OptionalTextAssignment("MODIFY WHEN", g.ParameterOptions().NoQuotes().NoEquals()). + OptionalSQL("REMOVE WHEN"). WithValidation(g.ValidIdentifier, "name"). - WithValidation(g.ExactlyOneValueSet, "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "ModifyAs", "ModifyWhen"), + WithValidation(g.ExactlyOneValueSet, "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "SetFinalize", "UnsetFinalize", "ModifyAs", "ModifyWhen", "RemoveWhen"), ). DropOperation( "https://docs.snowflake.com/en/sql-reference/sql/drop-task", diff --git a/pkg/sdk/tasks_dto_builders_gen.go b/pkg/sdk/tasks_dto_builders_gen.go index fd02c08b2e..7a0397bca2 100644 --- a/pkg/sdk/tasks_dto_builders_gen.go +++ b/pkg/sdk/tasks_dto_builders_gen.go @@ -14,68 +14,68 @@ func NewCreateTaskRequest( return &s } -func (s *CreateTaskRequest) WithOrReplace(OrReplace *bool) *CreateTaskRequest { - s.OrReplace = OrReplace +func (s *CreateTaskRequest) WithOrReplace(OrReplace bool) *CreateTaskRequest { + s.OrReplace = &OrReplace return s } -func (s *CreateTaskRequest) WithIfNotExists(IfNotExists *bool) *CreateTaskRequest { - s.IfNotExists = IfNotExists +func (s *CreateTaskRequest) WithIfNotExists(IfNotExists bool) *CreateTaskRequest { + s.IfNotExists = &IfNotExists return s } -func (s *CreateTaskRequest) WithWarehouse(Warehouse *CreateTaskWarehouseRequest) *CreateTaskRequest { - s.Warehouse = Warehouse +func (s *CreateTaskRequest) WithWarehouse(Warehouse CreateTaskWarehouseRequest) *CreateTaskRequest { + s.Warehouse = &Warehouse return s } -func (s *CreateTaskRequest) WithSchedule(Schedule *string) *CreateTaskRequest { - s.Schedule = Schedule +func (s *CreateTaskRequest) WithSchedule(Schedule string) *CreateTaskRequest { + s.Schedule = &Schedule return s } -func (s *CreateTaskRequest) WithConfig(Config *string) *CreateTaskRequest { - s.Config = Config +func (s *CreateTaskRequest) WithConfig(Config string) *CreateTaskRequest { + s.Config = &Config return s } -func (s *CreateTaskRequest) WithAllowOverlappingExecution(AllowOverlappingExecution *bool) *CreateTaskRequest { - s.AllowOverlappingExecution = AllowOverlappingExecution +func (s *CreateTaskRequest) WithAllowOverlappingExecution(AllowOverlappingExecution bool) *CreateTaskRequest { + s.AllowOverlappingExecution = &AllowOverlappingExecution return s } -func (s *CreateTaskRequest) WithSessionParameters(SessionParameters *SessionParameters) *CreateTaskRequest { - s.SessionParameters = SessionParameters +func (s *CreateTaskRequest) WithSessionParameters(SessionParameters SessionParameters) *CreateTaskRequest { + s.SessionParameters = &SessionParameters return s } -func (s *CreateTaskRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs *int) *CreateTaskRequest { - s.UserTaskTimeoutMs = UserTaskTimeoutMs +func (s *CreateTaskRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs int) *CreateTaskRequest { + s.UserTaskTimeoutMs = &UserTaskTimeoutMs return s } -func (s *CreateTaskRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures *int) *CreateTaskRequest { - s.SuspendTaskAfterNumFailures = SuspendTaskAfterNumFailures +func (s *CreateTaskRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures int) *CreateTaskRequest { + s.SuspendTaskAfterNumFailures = &SuspendTaskAfterNumFailures return s } -func (s *CreateTaskRequest) WithErrorIntegration(ErrorIntegration *string) *CreateTaskRequest { - s.ErrorIntegration = ErrorIntegration +func (s *CreateTaskRequest) WithErrorNotificationIntegration(ErrorNotificationIntegration AccountObjectIdentifier) *CreateTaskRequest { + s.ErrorNotificationIntegration = &ErrorNotificationIntegration return s } -func (s *CreateTaskRequest) WithCopyGrants(CopyGrants *bool) *CreateTaskRequest { - s.CopyGrants = CopyGrants +func (s *CreateTaskRequest) WithComment(Comment string) *CreateTaskRequest { + s.Comment = &Comment return s } -func (s *CreateTaskRequest) WithComment(Comment *string) *CreateTaskRequest { - s.Comment = Comment +func (s *CreateTaskRequest) WithFinalize(Finalize SchemaObjectIdentifier) *CreateTaskRequest { + s.Finalize = &Finalize return s } -func (s *CreateTaskRequest) WithAfter(After []SchemaObjectIdentifier) *CreateTaskRequest { - s.After = After +func (s *CreateTaskRequest) WithTaskAutoRetryAttempts(TaskAutoRetryAttempts int) *CreateTaskRequest { + s.TaskAutoRetryAttempts = &TaskAutoRetryAttempts return s } @@ -84,8 +84,18 @@ func (s *CreateTaskRequest) WithTag(Tag []TagAssociation) *CreateTaskRequest { return s } -func (s *CreateTaskRequest) WithWhen(When *string) *CreateTaskRequest { - s.When = When +func (s *CreateTaskRequest) WithUserTaskMinimumTriggerIntervalInSeconds(UserTaskMinimumTriggerIntervalInSeconds int) *CreateTaskRequest { + s.UserTaskMinimumTriggerIntervalInSeconds = &UserTaskMinimumTriggerIntervalInSeconds + return s +} + +func (s *CreateTaskRequest) WithAfter(After []SchemaObjectIdentifier) *CreateTaskRequest { + s.After = After + return s +} + +func (s *CreateTaskRequest) WithWhen(When string) *CreateTaskRequest { + s.When = &When return s } @@ -93,13 +103,88 @@ func NewCreateTaskWarehouseRequest() *CreateTaskWarehouseRequest { return &CreateTaskWarehouseRequest{} } -func (s *CreateTaskWarehouseRequest) WithWarehouse(Warehouse *AccountObjectIdentifier) *CreateTaskWarehouseRequest { - s.Warehouse = Warehouse +func (s *CreateTaskWarehouseRequest) WithWarehouse(Warehouse AccountObjectIdentifier) *CreateTaskWarehouseRequest { + s.Warehouse = &Warehouse + return s +} + +func (s *CreateTaskWarehouseRequest) WithUserTaskManagedInitialWarehouseSize(UserTaskManagedInitialWarehouseSize WarehouseSize) *CreateTaskWarehouseRequest { + s.UserTaskManagedInitialWarehouseSize = &UserTaskManagedInitialWarehouseSize + return s +} + +func NewCreateOrAlterTaskRequest( + name SchemaObjectIdentifier, + sql string, +) *CreateOrAlterTaskRequest { + s := CreateOrAlterTaskRequest{} + s.name = name + s.sql = sql + return &s +} + +func (s *CreateOrAlterTaskRequest) WithWarehouse(Warehouse CreateTaskWarehouseRequest) *CreateOrAlterTaskRequest { + s.Warehouse = &Warehouse + return s +} + +func (s *CreateOrAlterTaskRequest) WithSchedule(Schedule string) *CreateOrAlterTaskRequest { + s.Schedule = &Schedule + return s +} + +func (s *CreateOrAlterTaskRequest) WithConfig(Config string) *CreateOrAlterTaskRequest { + s.Config = &Config + return s +} + +func (s *CreateOrAlterTaskRequest) WithAllowOverlappingExecution(AllowOverlappingExecution bool) *CreateOrAlterTaskRequest { + s.AllowOverlappingExecution = &AllowOverlappingExecution + return s +} + +func (s *CreateOrAlterTaskRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs int) *CreateOrAlterTaskRequest { + s.UserTaskTimeoutMs = &UserTaskTimeoutMs + return s +} + +func (s *CreateOrAlterTaskRequest) WithSessionParameters(SessionParameters SessionParameters) *CreateOrAlterTaskRequest { + s.SessionParameters = &SessionParameters + return s +} + +func (s *CreateOrAlterTaskRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures int) *CreateOrAlterTaskRequest { + s.SuspendTaskAfterNumFailures = &SuspendTaskAfterNumFailures + return s +} + +func (s *CreateOrAlterTaskRequest) WithErrorNotificationIntegration(ErrorNotificationIntegration AccountObjectIdentifier) *CreateOrAlterTaskRequest { + s.ErrorNotificationIntegration = &ErrorNotificationIntegration + return s +} + +func (s *CreateOrAlterTaskRequest) WithComment(Comment string) *CreateOrAlterTaskRequest { + s.Comment = &Comment + return s +} + +func (s *CreateOrAlterTaskRequest) WithFinalize(Finalize SchemaObjectIdentifier) *CreateOrAlterTaskRequest { + s.Finalize = &Finalize + return s +} + +func (s *CreateOrAlterTaskRequest) WithTaskAutoRetryAttempts(TaskAutoRetryAttempts int) *CreateOrAlterTaskRequest { + s.TaskAutoRetryAttempts = &TaskAutoRetryAttempts + return s +} + +func (s *CreateOrAlterTaskRequest) WithAfter(After []SchemaObjectIdentifier) *CreateOrAlterTaskRequest { + s.After = After return s } -func (s *CreateTaskWarehouseRequest) WithUserTaskManagedInitialWarehouseSize(UserTaskManagedInitialWarehouseSize *WarehouseSize) *CreateTaskWarehouseRequest { - s.UserTaskManagedInitialWarehouseSize = UserTaskManagedInitialWarehouseSize +func (s *CreateOrAlterTaskRequest) WithWhen(When string) *CreateOrAlterTaskRequest { + s.When = &When return s } @@ -113,13 +198,13 @@ func NewCloneTaskRequest( return &s } -func (s *CloneTaskRequest) WithOrReplace(OrReplace *bool) *CloneTaskRequest { - s.OrReplace = OrReplace +func (s *CloneTaskRequest) WithOrReplace(OrReplace bool) *CloneTaskRequest { + s.OrReplace = &OrReplace return s } -func (s *CloneTaskRequest) WithCopyGrants(CopyGrants *bool) *CloneTaskRequest { - s.CopyGrants = CopyGrants +func (s *CloneTaskRequest) WithCopyGrants(CopyGrants bool) *CloneTaskRequest { + s.CopyGrants = &CopyGrants return s } @@ -131,18 +216,18 @@ func NewAlterTaskRequest( return &s } -func (s *AlterTaskRequest) WithIfExists(IfExists *bool) *AlterTaskRequest { - s.IfExists = IfExists +func (s *AlterTaskRequest) WithIfExists(IfExists bool) *AlterTaskRequest { + s.IfExists = &IfExists return s } -func (s *AlterTaskRequest) WithResume(Resume *bool) *AlterTaskRequest { - s.Resume = Resume +func (s *AlterTaskRequest) WithResume(Resume bool) *AlterTaskRequest { + s.Resume = &Resume return s } -func (s *AlterTaskRequest) WithSuspend(Suspend *bool) *AlterTaskRequest { - s.Suspend = Suspend +func (s *AlterTaskRequest) WithSuspend(Suspend bool) *AlterTaskRequest { + s.Suspend = &Suspend return s } @@ -156,13 +241,13 @@ func (s *AlterTaskRequest) WithAddAfter(AddAfter []SchemaObjectIdentifier) *Alte return s } -func (s *AlterTaskRequest) WithSet(Set *TaskSetRequest) *AlterTaskRequest { - s.Set = Set +func (s *AlterTaskRequest) WithSet(Set TaskSetRequest) *AlterTaskRequest { + s.Set = &Set return s } -func (s *AlterTaskRequest) WithUnset(Unset *TaskUnsetRequest) *AlterTaskRequest { - s.Unset = Unset +func (s *AlterTaskRequest) WithUnset(Unset TaskUnsetRequest) *AlterTaskRequest { + s.Unset = &Unset return s } @@ -176,13 +261,28 @@ func (s *AlterTaskRequest) WithUnsetTags(UnsetTags []ObjectIdentifier) *AlterTas return s } -func (s *AlterTaskRequest) WithModifyAs(ModifyAs *string) *AlterTaskRequest { - s.ModifyAs = ModifyAs +func (s *AlterTaskRequest) WithSetFinalize(SetFinalize SchemaObjectIdentifier) *AlterTaskRequest { + s.SetFinalize = &SetFinalize return s } -func (s *AlterTaskRequest) WithModifyWhen(ModifyWhen *string) *AlterTaskRequest { - s.ModifyWhen = ModifyWhen +func (s *AlterTaskRequest) WithUnsetFinalize(UnsetFinalize bool) *AlterTaskRequest { + s.UnsetFinalize = &UnsetFinalize + return s +} + +func (s *AlterTaskRequest) WithModifyAs(ModifyAs string) *AlterTaskRequest { + s.ModifyAs = &ModifyAs + return s +} + +func (s *AlterTaskRequest) WithModifyWhen(ModifyWhen string) *AlterTaskRequest { + s.ModifyWhen = &ModifyWhen + return s +} + +func (s *AlterTaskRequest) WithRemoveWhen(RemoveWhen bool) *AlterTaskRequest { + s.RemoveWhen = &RemoveWhen return s } @@ -190,53 +290,63 @@ func NewTaskSetRequest() *TaskSetRequest { return &TaskSetRequest{} } -func (s *TaskSetRequest) WithWarehouse(Warehouse *AccountObjectIdentifier) *TaskSetRequest { - s.Warehouse = Warehouse +func (s *TaskSetRequest) WithWarehouse(Warehouse AccountObjectIdentifier) *TaskSetRequest { + s.Warehouse = &Warehouse + return s +} + +func (s *TaskSetRequest) WithUserTaskManagedInitialWarehouseSize(UserTaskManagedInitialWarehouseSize WarehouseSize) *TaskSetRequest { + s.UserTaskManagedInitialWarehouseSize = &UserTaskManagedInitialWarehouseSize return s } -func (s *TaskSetRequest) WithUserTaskManagedInitialWarehouseSize(UserTaskManagedInitialWarehouseSize *WarehouseSize) *TaskSetRequest { - s.UserTaskManagedInitialWarehouseSize = UserTaskManagedInitialWarehouseSize +func (s *TaskSetRequest) WithSchedule(Schedule string) *TaskSetRequest { + s.Schedule = &Schedule return s } -func (s *TaskSetRequest) WithSchedule(Schedule *string) *TaskSetRequest { - s.Schedule = Schedule +func (s *TaskSetRequest) WithConfig(Config string) *TaskSetRequest { + s.Config = &Config return s } -func (s *TaskSetRequest) WithConfig(Config *string) *TaskSetRequest { - s.Config = Config +func (s *TaskSetRequest) WithAllowOverlappingExecution(AllowOverlappingExecution bool) *TaskSetRequest { + s.AllowOverlappingExecution = &AllowOverlappingExecution return s } -func (s *TaskSetRequest) WithAllowOverlappingExecution(AllowOverlappingExecution *bool) *TaskSetRequest { - s.AllowOverlappingExecution = AllowOverlappingExecution +func (s *TaskSetRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs int) *TaskSetRequest { + s.UserTaskTimeoutMs = &UserTaskTimeoutMs return s } -func (s *TaskSetRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs *int) *TaskSetRequest { - s.UserTaskTimeoutMs = UserTaskTimeoutMs +func (s *TaskSetRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures int) *TaskSetRequest { + s.SuspendTaskAfterNumFailures = &SuspendTaskAfterNumFailures return s } -func (s *TaskSetRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures *int) *TaskSetRequest { - s.SuspendTaskAfterNumFailures = SuspendTaskAfterNumFailures +func (s *TaskSetRequest) WithErrorNotificationIntegration(ErrorNotificationIntegration AccountObjectIdentifier) *TaskSetRequest { + s.ErrorNotificationIntegration = &ErrorNotificationIntegration return s } -func (s *TaskSetRequest) WithErrorIntegration(ErrorIntegration *string) *TaskSetRequest { - s.ErrorIntegration = ErrorIntegration +func (s *TaskSetRequest) WithComment(Comment string) *TaskSetRequest { + s.Comment = &Comment return s } -func (s *TaskSetRequest) WithComment(Comment *string) *TaskSetRequest { - s.Comment = Comment +func (s *TaskSetRequest) WithSessionParameters(SessionParameters SessionParameters) *TaskSetRequest { + s.SessionParameters = &SessionParameters return s } -func (s *TaskSetRequest) WithSessionParameters(SessionParameters *SessionParameters) *TaskSetRequest { - s.SessionParameters = SessionParameters +func (s *TaskSetRequest) WithTaskAutoRetryAttempts(TaskAutoRetryAttempts int) *TaskSetRequest { + s.TaskAutoRetryAttempts = &TaskAutoRetryAttempts + return s +} + +func (s *TaskSetRequest) WithUserTaskMinimumTriggerIntervalInSeconds(UserTaskMinimumTriggerIntervalInSeconds int) *TaskSetRequest { + s.UserTaskMinimumTriggerIntervalInSeconds = &UserTaskMinimumTriggerIntervalInSeconds return s } @@ -244,48 +354,58 @@ func NewTaskUnsetRequest() *TaskUnsetRequest { return &TaskUnsetRequest{} } -func (s *TaskUnsetRequest) WithWarehouse(Warehouse *bool) *TaskUnsetRequest { - s.Warehouse = Warehouse +func (s *TaskUnsetRequest) WithWarehouse(Warehouse bool) *TaskUnsetRequest { + s.Warehouse = &Warehouse + return s +} + +func (s *TaskUnsetRequest) WithSchedule(Schedule bool) *TaskUnsetRequest { + s.Schedule = &Schedule + return s +} + +func (s *TaskUnsetRequest) WithConfig(Config bool) *TaskUnsetRequest { + s.Config = &Config return s } -func (s *TaskUnsetRequest) WithSchedule(Schedule *bool) *TaskUnsetRequest { - s.Schedule = Schedule +func (s *TaskUnsetRequest) WithAllowOverlappingExecution(AllowOverlappingExecution bool) *TaskUnsetRequest { + s.AllowOverlappingExecution = &AllowOverlappingExecution return s } -func (s *TaskUnsetRequest) WithConfig(Config *bool) *TaskUnsetRequest { - s.Config = Config +func (s *TaskUnsetRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs bool) *TaskUnsetRequest { + s.UserTaskTimeoutMs = &UserTaskTimeoutMs return s } -func (s *TaskUnsetRequest) WithAllowOverlappingExecution(AllowOverlappingExecution *bool) *TaskUnsetRequest { - s.AllowOverlappingExecution = AllowOverlappingExecution +func (s *TaskUnsetRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures bool) *TaskUnsetRequest { + s.SuspendTaskAfterNumFailures = &SuspendTaskAfterNumFailures return s } -func (s *TaskUnsetRequest) WithUserTaskTimeoutMs(UserTaskTimeoutMs *bool) *TaskUnsetRequest { - s.UserTaskTimeoutMs = UserTaskTimeoutMs +func (s *TaskUnsetRequest) WithErrorIntegration(ErrorIntegration bool) *TaskUnsetRequest { + s.ErrorIntegration = &ErrorIntegration return s } -func (s *TaskUnsetRequest) WithSuspendTaskAfterNumFailures(SuspendTaskAfterNumFailures *bool) *TaskUnsetRequest { - s.SuspendTaskAfterNumFailures = SuspendTaskAfterNumFailures +func (s *TaskUnsetRequest) WithComment(Comment bool) *TaskUnsetRequest { + s.Comment = &Comment return s } -func (s *TaskUnsetRequest) WithErrorIntegration(ErrorIntegration *bool) *TaskUnsetRequest { - s.ErrorIntegration = ErrorIntegration +func (s *TaskUnsetRequest) WithTaskAutoRetryAttempts(TaskAutoRetryAttempts bool) *TaskUnsetRequest { + s.TaskAutoRetryAttempts = &TaskAutoRetryAttempts return s } -func (s *TaskUnsetRequest) WithComment(Comment *bool) *TaskUnsetRequest { - s.Comment = Comment +func (s *TaskUnsetRequest) WithUserTaskMinimumTriggerIntervalInSeconds(UserTaskMinimumTriggerIntervalInSeconds bool) *TaskUnsetRequest { + s.UserTaskMinimumTriggerIntervalInSeconds = &UserTaskMinimumTriggerIntervalInSeconds return s } -func (s *TaskUnsetRequest) WithSessionParametersUnset(SessionParametersUnset *SessionParametersUnset) *TaskUnsetRequest { - s.SessionParametersUnset = SessionParametersUnset +func (s *TaskUnsetRequest) WithSessionParametersUnset(SessionParametersUnset SessionParametersUnset) *TaskUnsetRequest { + s.SessionParametersUnset = &SessionParametersUnset return s } @@ -297,8 +417,8 @@ func NewDropTaskRequest( return &s } -func (s *DropTaskRequest) WithIfExists(IfExists *bool) *DropTaskRequest { - s.IfExists = IfExists +func (s *DropTaskRequest) WithIfExists(IfExists bool) *DropTaskRequest { + s.IfExists = &IfExists return s } @@ -306,33 +426,33 @@ func NewShowTaskRequest() *ShowTaskRequest { return &ShowTaskRequest{} } -func (s *ShowTaskRequest) WithTerse(Terse *bool) *ShowTaskRequest { - s.Terse = Terse +func (s *ShowTaskRequest) WithTerse(Terse bool) *ShowTaskRequest { + s.Terse = &Terse return s } -func (s *ShowTaskRequest) WithLike(Like *Like) *ShowTaskRequest { - s.Like = Like +func (s *ShowTaskRequest) WithLike(Like Like) *ShowTaskRequest { + s.Like = &Like return s } -func (s *ShowTaskRequest) WithIn(In *In) *ShowTaskRequest { - s.In = In +func (s *ShowTaskRequest) WithIn(In In) *ShowTaskRequest { + s.In = &In return s } -func (s *ShowTaskRequest) WithStartsWith(StartsWith *string) *ShowTaskRequest { - s.StartsWith = StartsWith +func (s *ShowTaskRequest) WithStartsWith(StartsWith string) *ShowTaskRequest { + s.StartsWith = &StartsWith return s } -func (s *ShowTaskRequest) WithRootOnly(RootOnly *bool) *ShowTaskRequest { - s.RootOnly = RootOnly +func (s *ShowTaskRequest) WithRootOnly(RootOnly bool) *ShowTaskRequest { + s.RootOnly = &RootOnly return s } -func (s *ShowTaskRequest) WithLimit(Limit *LimitFrom) *ShowTaskRequest { - s.Limit = Limit +func (s *ShowTaskRequest) WithLimit(Limit LimitFrom) *ShowTaskRequest { + s.Limit = &Limit return s } @@ -352,7 +472,7 @@ func NewExecuteTaskRequest( return &s } -func (s *ExecuteTaskRequest) WithRetryLast(RetryLast *bool) *ExecuteTaskRequest { - s.RetryLast = RetryLast +func (s *ExecuteTaskRequest) WithRetryLast(RetryLast bool) *ExecuteTaskRequest { + s.RetryLast = &RetryLast return s } diff --git a/pkg/sdk/tasks_dto_gen.go b/pkg/sdk/tasks_dto_gen.go index aa58a0c7aa..e6a2726b4e 100644 --- a/pkg/sdk/tasks_dto_gen.go +++ b/pkg/sdk/tasks_dto_gen.go @@ -3,42 +3,67 @@ package sdk //go:generate go run ./dto-builder-generator/main.go var ( - _ optionsProvider[CreateTaskOptions] = new(CreateTaskRequest) - _ optionsProvider[CloneTaskOptions] = new(CloneTaskRequest) - _ optionsProvider[AlterTaskOptions] = new(AlterTaskRequest) - _ optionsProvider[DropTaskOptions] = new(DropTaskRequest) - _ optionsProvider[ShowTaskOptions] = new(ShowTaskRequest) - _ optionsProvider[DescribeTaskOptions] = new(DescribeTaskRequest) - _ optionsProvider[ExecuteTaskOptions] = new(ExecuteTaskRequest) + _ optionsProvider[CreateTaskOptions] = new(CreateTaskRequest) + _ optionsProvider[CreateOrAlterTaskOptions] = new(CreateOrAlterTaskRequest) + _ optionsProvider[CloneTaskOptions] = new(CloneTaskRequest) + _ optionsProvider[AlterTaskOptions] = new(AlterTaskRequest) + _ optionsProvider[DropTaskOptions] = new(DropTaskRequest) + _ optionsProvider[ShowTaskOptions] = new(ShowTaskRequest) + _ optionsProvider[DescribeTaskOptions] = new(DescribeTaskRequest) + _ optionsProvider[ExecuteTaskOptions] = new(ExecuteTaskRequest) ) type CreateTaskRequest struct { - OrReplace *bool - IfNotExists *bool - name SchemaObjectIdentifier // required - Warehouse *CreateTaskWarehouseRequest - Schedule *string - Config *string - AllowOverlappingExecution *bool - SessionParameters *SessionParameters - UserTaskTimeoutMs *int - SuspendTaskAfterNumFailures *int - ErrorIntegration *string - CopyGrants *bool - Comment *string - After []SchemaObjectIdentifier - Tag []TagAssociation - When *string - sql string // required + OrReplace *bool + IfNotExists *bool + name SchemaObjectIdentifier // required + Warehouse *CreateTaskWarehouseRequest + Schedule *string + Config *string + AllowOverlappingExecution *bool + SessionParameters *SessionParameters + UserTaskTimeoutMs *int + SuspendTaskAfterNumFailures *int + ErrorNotificationIntegration *AccountObjectIdentifier + Comment *string + Finalize *SchemaObjectIdentifier + TaskAutoRetryAttempts *int + Tag []TagAssociation + UserTaskMinimumTriggerIntervalInSeconds *int + After []SchemaObjectIdentifier + When *string + sql string // required +} + +type CreateTaskWarehouseRequest struct { + Warehouse *AccountObjectIdentifier + UserTaskManagedInitialWarehouseSize *WarehouseSize } func (r *CreateTaskRequest) GetName() SchemaObjectIdentifier { return r.name } -type CreateTaskWarehouseRequest struct { - Warehouse *AccountObjectIdentifier - UserTaskManagedInitialWarehouseSize *WarehouseSize +type CreateOrAlterTaskRequest struct { + name SchemaObjectIdentifier // required + Warehouse *CreateTaskWarehouseRequest + Schedule *string + Config *string + AllowOverlappingExecution *bool + UserTaskTimeoutMs *int + SessionParameters *SessionParameters + SuspendTaskAfterNumFailures *int + ErrorNotificationIntegration *AccountObjectIdentifier + Comment *string + Finalize *SchemaObjectIdentifier + TaskAutoRetryAttempts *int + After []SchemaObjectIdentifier + When *string + sql string // required +} + +func (r *CreateOrAlterTaskRequest) GetName() SchemaObjectIdentifier { + return r.name } type CloneTaskRequest struct { @@ -48,48 +73,55 @@ type CloneTaskRequest struct { CopyGrants *bool } -func (r *CloneTaskRequest) GetName() SchemaObjectIdentifier { - return r.name +type AlterTaskRequest struct { + IfExists *bool + name SchemaObjectIdentifier // required + Resume *bool + Suspend *bool + RemoveAfter []SchemaObjectIdentifier + AddAfter []SchemaObjectIdentifier + Set *TaskSetRequest + Unset *TaskUnsetRequest + SetTags []TagAssociation + UnsetTags []ObjectIdentifier + SetFinalize *SchemaObjectIdentifier + UnsetFinalize *bool + ModifyAs *string + ModifyWhen *string + RemoveWhen *bool } -type AlterTaskRequest struct { - IfExists *bool - name SchemaObjectIdentifier // required - Resume *bool - Suspend *bool - RemoveAfter []SchemaObjectIdentifier - AddAfter []SchemaObjectIdentifier - Set *TaskSetRequest - Unset *TaskUnsetRequest - SetTags []TagAssociation - UnsetTags []ObjectIdentifier - ModifyAs *string - ModifyWhen *string +func (r *AlterTaskRequest) GetName() SchemaObjectIdentifier { + return r.name } type TaskSetRequest struct { - Warehouse *AccountObjectIdentifier - UserTaskManagedInitialWarehouseSize *WarehouseSize - Schedule *string - Config *string - AllowOverlappingExecution *bool - UserTaskTimeoutMs *int - SuspendTaskAfterNumFailures *int - ErrorIntegration *string - Comment *string - SessionParameters *SessionParameters + Warehouse *AccountObjectIdentifier + UserTaskManagedInitialWarehouseSize *WarehouseSize + Schedule *string + Config *string + AllowOverlappingExecution *bool + UserTaskTimeoutMs *int + SuspendTaskAfterNumFailures *int + ErrorNotificationIntegration *AccountObjectIdentifier + Comment *string + SessionParameters *SessionParameters + TaskAutoRetryAttempts *int + UserTaskMinimumTriggerIntervalInSeconds *int } type TaskUnsetRequest struct { - Warehouse *bool - Schedule *bool - Config *bool - AllowOverlappingExecution *bool - UserTaskTimeoutMs *bool - SuspendTaskAfterNumFailures *bool - ErrorIntegration *bool - Comment *bool - SessionParametersUnset *SessionParametersUnset + Warehouse *bool + Schedule *bool + Config *bool + AllowOverlappingExecution *bool + UserTaskTimeoutMs *bool + SuspendTaskAfterNumFailures *bool + ErrorIntegration *bool + Comment *bool + TaskAutoRetryAttempts *bool + UserTaskMinimumTriggerIntervalInSeconds *bool + SessionParametersUnset *SessionParametersUnset } type DropTaskRequest struct { diff --git a/pkg/sdk/tasks_gen.go b/pkg/sdk/tasks_gen.go index ca70c458ae..56123086ff 100644 --- a/pkg/sdk/tasks_gen.go +++ b/pkg/sdk/tasks_gen.go @@ -7,6 +7,7 @@ import ( type Tasks interface { Create(ctx context.Context, request *CreateTaskRequest) error + CreateOrAlter(ctx context.Context, request *CreateOrAlterTaskRequest) error Clone(ctx context.Context, request *CloneTaskRequest) error Alter(ctx context.Context, request *AlterTaskRequest) error Drop(ctx context.Context, request *DropTaskRequest) error @@ -20,26 +21,28 @@ type Tasks interface { // CreateTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/create-task. type CreateTaskOptions struct { - create bool `ddl:"static" sql:"CREATE"` - OrReplace *bool `ddl:"keyword" sql:"OR REPLACE"` - task bool `ddl:"static" sql:"TASK"` - IfNotExists *bool `ddl:"keyword" sql:"IF NOT EXISTS"` - name SchemaObjectIdentifier `ddl:"identifier"` - Warehouse *CreateTaskWarehouse `ddl:"keyword"` - Schedule *string `ddl:"parameter,single_quotes" sql:"SCHEDULE"` - Config *string `ddl:"parameter,no_quotes" sql:"CONFIG"` - AllowOverlappingExecution *bool `ddl:"parameter" sql:"ALLOW_OVERLAPPING_EXECUTION"` - SessionParameters *SessionParameters `ddl:"list,no_parentheses"` - UserTaskTimeoutMs *int `ddl:"parameter" sql:"USER_TASK_TIMEOUT_MS"` - SuspendTaskAfterNumFailures *int `ddl:"parameter" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` - ErrorIntegration *string `ddl:"parameter,no_quotes" sql:"ERROR_INTEGRATION"` - CopyGrants *bool `ddl:"keyword" sql:"COPY GRANTS"` - Comment *string `ddl:"parameter,single_quotes" sql:"COMMENT"` - After []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"AFTER"` - Tag []TagAssociation `ddl:"keyword,parentheses" sql:"TAG"` - When *string `ddl:"parameter,no_quotes,no_equals" sql:"WHEN"` - as bool `ddl:"static" sql:"AS"` - sql string `ddl:"keyword,no_quotes"` + create bool `ddl:"static" sql:"CREATE"` + OrReplace *bool `ddl:"keyword" sql:"OR REPLACE"` + task bool `ddl:"static" sql:"TASK"` + IfNotExists *bool `ddl:"keyword" sql:"IF NOT EXISTS"` + name SchemaObjectIdentifier `ddl:"identifier"` + Warehouse *CreateTaskWarehouse `ddl:"keyword"` + Schedule *string `ddl:"parameter,single_quotes" sql:"SCHEDULE"` + Config *string `ddl:"parameter,no_quotes" sql:"CONFIG"` + AllowOverlappingExecution *bool `ddl:"parameter" sql:"ALLOW_OVERLAPPING_EXECUTION"` + SessionParameters *SessionParameters `ddl:"list,no_parentheses"` + UserTaskTimeoutMs *int `ddl:"parameter" sql:"USER_TASK_TIMEOUT_MS"` + SuspendTaskAfterNumFailures *int `ddl:"parameter" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` + ErrorNotificationIntegration *AccountObjectIdentifier `ddl:"identifier,equals" sql:"ERROR_INTEGRATION"` + Comment *string `ddl:"parameter,single_quotes" sql:"COMMENT"` + Finalize *SchemaObjectIdentifier `ddl:"identifier,equals" sql:"FINALIZE"` + TaskAutoRetryAttempts *int `ddl:"parameter" sql:"TASK_AUTO_RETRY_ATTEMPTS"` + Tag []TagAssociation `ddl:"keyword,parentheses" sql:"TAG"` + UserTaskMinimumTriggerIntervalInSeconds *int `ddl:"parameter" sql:"USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS"` + After []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"AFTER"` + When *string `ddl:"parameter,no_quotes,no_equals" sql:"WHEN"` + as bool `ddl:"static" sql:"AS"` + sql string `ddl:"keyword,no_quotes"` } type CreateTaskWarehouse struct { @@ -47,7 +50,29 @@ type CreateTaskWarehouse struct { UserTaskManagedInitialWarehouseSize *WarehouseSize `ddl:"parameter,single_quotes" sql:"USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE"` } -// CloneTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/create-task#variant-syntax. +// CreateOrAlterTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/create-task#create-or-alter-task. +type CreateOrAlterTaskOptions struct { + createOrAlter bool `ddl:"static" sql:"CREATE OR ALTER"` + task bool `ddl:"static" sql:"TASK"` + name SchemaObjectIdentifier `ddl:"identifier"` + Warehouse *CreateTaskWarehouse `ddl:"keyword"` + Schedule *string `ddl:"parameter,single_quotes" sql:"SCHEDULE"` + Config *string `ddl:"parameter,no_quotes" sql:"CONFIG"` + AllowOverlappingExecution *bool `ddl:"parameter" sql:"ALLOW_OVERLAPPING_EXECUTION"` + UserTaskTimeoutMs *int `ddl:"parameter" sql:"USER_TASK_TIMEOUT_MS"` + SessionParameters *SessionParameters `ddl:"list,no_parentheses"` + SuspendTaskAfterNumFailures *int `ddl:"parameter" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` + ErrorNotificationIntegration *AccountObjectIdentifier `ddl:"identifier,equals" sql:"ERROR_INTEGRATION"` + Comment *string `ddl:"parameter,single_quotes" sql:"COMMENT"` + Finalize *SchemaObjectIdentifier `ddl:"identifier,equals" sql:"FINALIZE"` + TaskAutoRetryAttempts *int `ddl:"parameter" sql:"TASK_AUTO_RETRY_ATTEMPTS"` + After []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"AFTER"` + When *string `ddl:"parameter,no_quotes,no_equals" sql:"WHEN"` + as bool `ddl:"static" sql:"AS"` + sql string `ddl:"keyword,no_quotes"` +} + +// CloneTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/create-task#create-task-clone. type CloneTaskOptions struct { create bool `ddl:"static" sql:"CREATE"` OrReplace *bool `ddl:"keyword" sql:"OR REPLACE"` @@ -60,45 +85,52 @@ type CloneTaskOptions struct { // AlterTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/alter-task. type AlterTaskOptions struct { - alter bool `ddl:"static" sql:"ALTER"` - task bool `ddl:"static" sql:"TASK"` - IfExists *bool `ddl:"keyword" sql:"IF EXISTS"` - name SchemaObjectIdentifier `ddl:"identifier"` - Resume *bool `ddl:"keyword" sql:"RESUME"` - Suspend *bool `ddl:"keyword" sql:"SUSPEND"` - RemoveAfter []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"REMOVE AFTER"` - AddAfter []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"ADD AFTER"` - Set *TaskSet `ddl:"list,no_parentheses" sql:"SET"` - Unset *TaskUnset `ddl:"list,no_parentheses" sql:"UNSET"` - SetTags []TagAssociation `ddl:"keyword" sql:"SET TAG"` - UnsetTags []ObjectIdentifier `ddl:"keyword" sql:"UNSET TAG"` - ModifyAs *string `ddl:"parameter,no_quotes,no_equals" sql:"MODIFY AS"` - ModifyWhen *string `ddl:"parameter,no_quotes,no_equals" sql:"MODIFY WHEN"` + alter bool `ddl:"static" sql:"ALTER"` + task bool `ddl:"static" sql:"TASK"` + IfExists *bool `ddl:"keyword" sql:"IF EXISTS"` + name SchemaObjectIdentifier `ddl:"identifier"` + Resume *bool `ddl:"keyword" sql:"RESUME"` + Suspend *bool `ddl:"keyword" sql:"SUSPEND"` + RemoveAfter []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"REMOVE AFTER"` + AddAfter []SchemaObjectIdentifier `ddl:"parameter,no_equals" sql:"ADD AFTER"` + Set *TaskSet `ddl:"list,no_parentheses" sql:"SET"` + Unset *TaskUnset `ddl:"list,no_parentheses" sql:"UNSET"` + SetTags []TagAssociation `ddl:"keyword" sql:"SET TAG"` + UnsetTags []ObjectIdentifier `ddl:"keyword" sql:"UNSET TAG"` + SetFinalize *SchemaObjectIdentifier `ddl:"identifier,equals" sql:"SET FINALIZE"` + UnsetFinalize *bool `ddl:"keyword" sql:"UNSET FINALIZE"` + ModifyAs *string `ddl:"parameter,no_quotes,no_equals" sql:"MODIFY AS"` + ModifyWhen *string `ddl:"parameter,no_quotes,no_equals" sql:"MODIFY WHEN"` + RemoveWhen *bool `ddl:"keyword" sql:"REMOVE WHEN"` } type TaskSet struct { - Warehouse *AccountObjectIdentifier `ddl:"identifier,equals" sql:"WAREHOUSE"` - UserTaskManagedInitialWarehouseSize *WarehouseSize `ddl:"parameter,single_quotes" sql:"USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE"` - Schedule *string `ddl:"parameter,single_quotes" sql:"SCHEDULE"` - Config *string `ddl:"parameter,no_quotes" sql:"CONFIG"` - AllowOverlappingExecution *bool `ddl:"parameter" sql:"ALLOW_OVERLAPPING_EXECUTION"` - UserTaskTimeoutMs *int `ddl:"parameter" sql:"USER_TASK_TIMEOUT_MS"` - SuspendTaskAfterNumFailures *int `ddl:"parameter" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` - ErrorIntegration *string `ddl:"parameter,no_quotes" sql:"ERROR_INTEGRATION"` - Comment *string `ddl:"parameter,single_quotes" sql:"COMMENT"` - SessionParameters *SessionParameters `ddl:"list,no_parentheses"` + Warehouse *AccountObjectIdentifier `ddl:"identifier,equals" sql:"WAREHOUSE"` + UserTaskManagedInitialWarehouseSize *WarehouseSize `ddl:"parameter,single_quotes" sql:"USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE"` + Schedule *string `ddl:"parameter,single_quotes" sql:"SCHEDULE"` + Config *string `ddl:"parameter,no_quotes" sql:"CONFIG"` + AllowOverlappingExecution *bool `ddl:"parameter" sql:"ALLOW_OVERLAPPING_EXECUTION"` + UserTaskTimeoutMs *int `ddl:"parameter" sql:"USER_TASK_TIMEOUT_MS"` + SuspendTaskAfterNumFailures *int `ddl:"parameter" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` + ErrorNotificationIntegration *AccountObjectIdentifier `ddl:"identifier,equals" sql:"ERROR_INTEGRATION"` + Comment *string `ddl:"parameter,single_quotes" sql:"COMMENT"` + SessionParameters *SessionParameters `ddl:"list,no_parentheses"` + TaskAutoRetryAttempts *int `ddl:"parameter" sql:"TASK_AUTO_RETRY_ATTEMPTS"` + UserTaskMinimumTriggerIntervalInSeconds *int `ddl:"parameter" sql:"USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS"` } type TaskUnset struct { - Warehouse *bool `ddl:"keyword" sql:"WAREHOUSE"` - Schedule *bool `ddl:"keyword" sql:"SCHEDULE"` - Config *bool `ddl:"keyword" sql:"CONFIG"` - AllowOverlappingExecution *bool `ddl:"keyword" sql:"ALLOW_OVERLAPPING_EXECUTION"` - UserTaskTimeoutMs *bool `ddl:"keyword" sql:"USER_TASK_TIMEOUT_MS"` - SuspendTaskAfterNumFailures *bool `ddl:"keyword" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` - ErrorIntegration *bool `ddl:"keyword" sql:"ERROR_INTEGRATION"` - Comment *bool `ddl:"keyword" sql:"COMMENT"` - SessionParametersUnset *SessionParametersUnset `ddl:"list,no_parentheses"` + Warehouse *bool `ddl:"keyword" sql:"WAREHOUSE"` + Schedule *bool `ddl:"keyword" sql:"SCHEDULE"` + Config *bool `ddl:"keyword" sql:"CONFIG"` + AllowOverlappingExecution *bool `ddl:"keyword" sql:"ALLOW_OVERLAPPING_EXECUTION"` + UserTaskTimeoutMs *bool `ddl:"keyword" sql:"USER_TASK_TIMEOUT_MS"` + SuspendTaskAfterNumFailures *bool `ddl:"keyword" sql:"SUSPEND_TASK_AFTER_NUM_FAILURES"` + ErrorIntegration *bool `ddl:"keyword" sql:"ERROR_INTEGRATION"` + Comment *bool `ddl:"keyword" sql:"COMMENT"` + TaskAutoRetryAttempts *bool `ddl:"keyword" sql:"TASK_AUTO_RETRY_ATTEMPTS"` + UserTaskMinimumTriggerIntervalInSeconds *bool `ddl:"keyword" sql:"USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS"` + SessionParametersUnset *SessionParametersUnset `ddl:"list,no_parentheses"` } // DropTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/drop-task. @@ -116,7 +148,7 @@ type ShowTaskOptions struct { tasks bool `ddl:"static" sql:"TASKS"` Like *Like `ddl:"keyword" sql:"LIKE"` In *In `ddl:"keyword" sql:"IN"` - StartsWith *string `ddl:"parameter,no_equals,single_quotes" sql:"STARTS WITH"` + StartsWith *string `ddl:"parameter,single_quotes,no_equals" sql:"STARTS WITH"` RootOnly *bool `ddl:"keyword" sql:"ROOT ONLY"` Limit *LimitFrom `ddl:"keyword" sql:"LIMIT"` } @@ -124,24 +156,26 @@ type ShowTaskOptions struct { type taskDBRow struct { CreatedOn string `db:"created_on"` Name string `db:"name"` - Id sql.NullString `db:"id"` + Id string `db:"id"` DatabaseName string `db:"database_name"` SchemaName string `db:"schema_name"` - Owner sql.NullString `db:"owner"` + Owner string `db:"owner"` Comment sql.NullString `db:"comment"` Warehouse sql.NullString `db:"warehouse"` Schedule sql.NullString `db:"schedule"` - Predecessors sql.NullString `db:"predecessors"` - State sql.NullString `db:"state"` - Definition sql.NullString `db:"definition"` + Predecessors string `db:"predecessors"` + State string `db:"state"` + Definition string `db:"definition"` Condition sql.NullString `db:"condition"` - AllowOverlappingExecution sql.NullString `db:"allow_overlapping_execution"` + AllowOverlappingExecution string `db:"allow_overlapping_execution"` ErrorIntegration sql.NullString `db:"error_integration"` LastCommittedOn sql.NullString `db:"last_committed_on"` LastSuspendedOn sql.NullString `db:"last_suspended_on"` - OwnerRoleType sql.NullString `db:"owner_role_type"` + OwnerRoleType string `db:"owner_role_type"` Config sql.NullString `db:"config"` Budget sql.NullString `db:"budget"` + TaskRelations string `db:"task_relations"` + LastSuspendedReason sql.NullString `db:"last_suspended_reason"` } type Task struct { @@ -159,12 +193,18 @@ type Task struct { Definition string Condition string AllowOverlappingExecution bool - ErrorIntegration string + ErrorIntegration *AccountObjectIdentifier LastCommittedOn string LastSuspendedOn string OwnerRoleType string Config string Budget string + TaskRelations TaskRelations + LastSuspendedReason string +} + +func (v *Task) ID() SchemaObjectIdentifier { + return NewSchemaObjectIdentifier(v.DatabaseName, v.SchemaName, v.Name) } // DescribeTaskOptions is based on https://docs.snowflake.com/en/sql-reference/sql/desc-task. @@ -181,18 +221,3 @@ type ExecuteTaskOptions struct { name SchemaObjectIdentifier `ddl:"identifier"` RetryLast *bool `ddl:"keyword" sql:"RETRY LAST"` } - -func (v *Task) ID() SchemaObjectIdentifier { - return NewSchemaObjectIdentifier(v.DatabaseName, v.SchemaName, v.Name) -} - -type TaskState string - -const ( - TaskStateStarted TaskState = "started" - TaskStateSuspended TaskState = "suspended" -) - -func (v *Task) IsStarted() bool { - return v.State == TaskStateStarted -} diff --git a/pkg/sdk/tasks_gen_test.go b/pkg/sdk/tasks_gen_test.go index 926958427e..53aa7d8ea4 100644 --- a/pkg/sdk/tasks_gen_test.go +++ b/pkg/sdk/tasks_gen_test.go @@ -54,39 +54,117 @@ func TestTasks_Create(t *testing.T) { }) t.Run("with initial warehouse size", func(t *testing.T) { - req := NewCreateTaskRequest(id, sql). - WithWarehouse(NewCreateTaskWarehouseRequest().WithUserTaskManagedInitialWarehouseSize(Pointer(WarehouseSizeXSmall))) - assertOptsValidAndSQLEquals(t, req.toOpts(), "CREATE TASK %s USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL' AS %s", id.FullyQualifiedName(), sql) + opts := defaultOpts() + opts.Warehouse = &CreateTaskWarehouse{ + UserTaskManagedInitialWarehouseSize: Pointer(WarehouseSizeXSmall), + } + assertOptsValidAndSQLEquals(t, opts, "CREATE TASK %s USER_TASK_MANAGED_INITIAL_WAREHOUSE_SIZE = 'XSMALL' AS %s", id.FullyQualifiedName(), sql) }) t.Run("all options", func(t *testing.T) { warehouseId := randomAccountObjectIdentifier() otherTaskId := randomSchemaObjectIdentifier() tagId := randomSchemaObjectIdentifier() + finalizerId := randomSchemaObjectIdentifier() + opts := defaultOpts() + + opts.OrReplace = Bool(true) + opts.Warehouse = &CreateTaskWarehouse{ + Warehouse: &warehouseId, + } + opts.Schedule = String("10 MINUTE") + opts.Config = String(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`) + opts.AllowOverlappingExecution = Bool(true) + opts.SessionParameters = &SessionParameters{ + JSONIndent: Int(10), + LockTimeout: Int(5), + } + opts.UserTaskTimeoutMs = Int(5) + opts.SuspendTaskAfterNumFailures = Int(6) + opts.ErrorNotificationIntegration = Pointer(NewAccountObjectIdentifier("some_error_integration")) + opts.Comment = String("some comment") + opts.Finalize = &finalizerId + opts.TaskAutoRetryAttempts = Int(10) + opts.Tag = []TagAssociation{{ + Name: tagId, + Value: "v1", + }} + opts.UserTaskMinimumTriggerIntervalInSeconds = Int(10) + opts.After = []SchemaObjectIdentifier{otherTaskId} + opts.When = String(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`) + + assertOptsValidAndSQLEquals(t, opts, "CREATE OR REPLACE TASK %s WAREHOUSE = %s SCHEDULE = '10 MINUTE' CONFIG = $${\"output_dir\": \"/temp/test_directory/\", \"learning_rate\": 0.1}$$ ALLOW_OVERLAPPING_EXECUTION = true JSON_INDENT = 10, LOCK_TIMEOUT = 5 USER_TASK_TIMEOUT_MS = 5 SUSPEND_TASK_AFTER_NUM_FAILURES = 6 ERROR_INTEGRATION = \"some_error_integration\" COMMENT = 'some comment' FINALIZE = %s TASK_AUTO_RETRY_ATTEMPTS = 10 TAG (%s = 'v1') USER_TASK_MINIMUM_TRIGGER_INTERVAL_IN_SECONDS = 10 AFTER %s WHEN SYSTEM$STREAM_HAS_DATA('MYSTREAM') AS SELECT CURRENT_TIMESTAMP", id.FullyQualifiedName(), warehouseId.FullyQualifiedName(), finalizerId.FullyQualifiedName(), tagId.FullyQualifiedName(), otherTaskId.FullyQualifiedName()) + }) +} + +func TestTasks_CreateOrAlter(t *testing.T) { + id := randomSchemaObjectIdentifier() + sql := "SELECT CURRENT_TIMESTAMP" + + // Minimal valid CreateTaskOptions + defaultOpts := func() *CreateOrAlterTaskOptions { + return &CreateOrAlterTaskOptions{ + name: id, + sql: sql, + } + } + + t.Run("validation: nil options", func(t *testing.T) { + var opts *CreateOrAlterTaskOptions = nil + assertOptsInvalidJoinedErrors(t, opts, ErrNilOptions) + }) + + t.Run("validation: valid identifier for [opts.name]", func(t *testing.T) { + opts := defaultOpts() + opts.name = emptySchemaObjectIdentifier + assertOptsInvalidJoinedErrors(t, opts, ErrInvalidObjectIdentifier) + }) + + t.Run("validation: exactly one field from [opts.Warehouse.Warehouse opts.Warehouse.UserTaskManagedInitialWarehouseSize] should be present", func(t *testing.T) { + opts := defaultOpts() + opts.Warehouse = &CreateTaskWarehouse{} + assertOptsInvalidJoinedErrors(t, opts, errExactlyOneOf("CreateOrAlterTaskOptions.CreateTaskWarehouse", "Warehouse", "UserTaskManagedInitialWarehouseSize")) + }) - req := NewCreateTaskRequest(id, sql). - WithOrReplace(Bool(true)). - WithWarehouse(NewCreateTaskWarehouseRequest().WithWarehouse(&warehouseId)). - WithSchedule(String("10 MINUTE")). - WithConfig(String(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`)). - WithAllowOverlappingExecution(Bool(true)). - WithSessionParameters(&SessionParameters{ - JSONIndent: Int(10), - LockTimeout: Int(5), - }). - WithUserTaskTimeoutMs(Int(5)). - WithSuspendTaskAfterNumFailures(Int(6)). - WithErrorIntegration(String("some_error_integration")). - WithCopyGrants(Bool(true)). - WithComment(String("some comment")). - WithAfter([]SchemaObjectIdentifier{otherTaskId}). - WithTag([]TagAssociation{{ - Name: tagId, - Value: "v1", - }}). - WithWhen(String(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`)) - - assertOptsValidAndSQLEquals(t, req.toOpts(), "CREATE OR REPLACE TASK %s WAREHOUSE = %s SCHEDULE = '10 MINUTE' CONFIG = $${\"output_dir\": \"/temp/test_directory/\", \"learning_rate\": 0.1}$$ ALLOW_OVERLAPPING_EXECUTION = true JSON_INDENT = 10, LOCK_TIMEOUT = 5 USER_TASK_TIMEOUT_MS = 5 SUSPEND_TASK_AFTER_NUM_FAILURES = 6 ERROR_INTEGRATION = some_error_integration COPY GRANTS COMMENT = 'some comment' AFTER %s TAG (%s = 'v1') WHEN SYSTEM$STREAM_HAS_DATA('MYSTREAM') AS SELECT CURRENT_TIMESTAMP", id.FullyQualifiedName(), warehouseId.FullyQualifiedName(), otherTaskId.FullyQualifiedName(), tagId.FullyQualifiedName()) + t.Run("validation: opts.SessionParameters.SessionParameters should be valid", func(t *testing.T) { + opts := defaultOpts() + opts.SessionParameters = &SessionParameters{ + JSONIndent: Int(25), + } + assertOptsInvalidJoinedErrors(t, opts, errIntBetween("SessionParameters", "JSONIndent", 0, 16)) + }) + + t.Run("basic", func(t *testing.T) { + opts := defaultOpts() + assertOptsValidAndSQLEquals(t, opts, "CREATE OR ALTER TASK %s AS %s", id.FullyQualifiedName(), sql) + }) + + t.Run("all options", func(t *testing.T) { + warehouseId := randomAccountObjectIdentifier() + otherTaskId := randomSchemaObjectIdentifier() + finalizerId := randomSchemaObjectIdentifier() + opts := defaultOpts() + + opts.Warehouse = &CreateTaskWarehouse{ + Warehouse: &warehouseId, + } + opts.Schedule = String("10 MINUTE") + opts.Config = String(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`) + opts.AllowOverlappingExecution = Bool(true) + opts.UserTaskTimeoutMs = Int(5) + opts.SessionParameters = &SessionParameters{ + JSONIndent: Int(10), + LockTimeout: Int(5), + } + opts.SuspendTaskAfterNumFailures = Int(6) + opts.ErrorNotificationIntegration = Pointer(NewAccountObjectIdentifier("some_error_integration")) + opts.Comment = String("some comment") + opts.Finalize = &finalizerId + opts.TaskAutoRetryAttempts = Int(10) + opts.After = []SchemaObjectIdentifier{otherTaskId} + opts.When = String(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`) + + assertOptsValidAndSQLEquals(t, opts, "CREATE OR ALTER TASK %s WAREHOUSE = %s SCHEDULE = '10 MINUTE' CONFIG = $${\"output_dir\": \"/temp/test_directory/\", \"learning_rate\": 0.1}$$ ALLOW_OVERLAPPING_EXECUTION = true USER_TASK_TIMEOUT_MS = 5 JSON_INDENT = 10, LOCK_TIMEOUT = 5 SUSPEND_TASK_AFTER_NUM_FAILURES = 6 ERROR_INTEGRATION = \"some_error_integration\" COMMENT = 'some comment' FINALIZE = %s TASK_AUTO_RETRY_ATTEMPTS = 10 AFTER %s WHEN SYSTEM$STREAM_HAS_DATA('MYSTREAM') AS SELECT CURRENT_TIMESTAMP", id.FullyQualifiedName(), warehouseId.FullyQualifiedName(), finalizerId.FullyQualifiedName(), otherTaskId.FullyQualifiedName()) }) } @@ -156,20 +234,20 @@ func TestTasks_Alter(t *testing.T) { t.Run("validation: exactly one field from [opts.Resume opts.Suspend opts.RemoveAfter opts.AddAfter opts.Set opts.Unset opts.SetTags opts.UnsetTags opts.ModifyAs opts.ModifyWhen] should be present", func(t *testing.T) { opts := defaultOpts() - assertOptsInvalidJoinedErrors(t, opts, errExactlyOneOf("AlterTaskOptions", "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "ModifyAs", "ModifyWhen")) + assertOptsInvalidJoinedErrors(t, opts, errExactlyOneOf("AlterTaskOptions", "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "SetFinalize", "UnsetFinalize", "ModifyAs", "ModifyWhen", "RemoveWhen")) }) t.Run("validation: exactly one field from [opts.Resume opts.Suspend opts.RemoveAfter opts.AddAfter opts.Set opts.Unset opts.SetTags opts.UnsetTags opts.ModifyAs opts.ModifyWhen] should be present - more present", func(t *testing.T) { opts := defaultOpts() opts.Resume = Bool(true) opts.Suspend = Bool(true) - assertOptsInvalidJoinedErrors(t, opts, errExactlyOneOf("AlterTaskOptions", "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "ModifyAs", "ModifyWhen")) + assertOptsInvalidJoinedErrors(t, opts, errExactlyOneOf("AlterTaskOptions", "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "SetFinalize", "UnsetFinalize", "ModifyAs", "ModifyWhen", "RemoveWhen")) }) t.Run("validation: at least one of the fields [opts.Set.Warehouse opts.Set.UserTaskManagedInitialWarehouseSize opts.Set.Schedule opts.Set.Config opts.Set.AllowOverlappingExecution opts.Set.UserTaskTimeoutMs opts.Set.SuspendTaskAfterNumFailures opts.Set.ErrorIntegration opts.Set.Comment opts.Set.SessionParameters] should be set", func(t *testing.T) { opts := defaultOpts() opts.Set = &TaskSet{} - assertOptsInvalidJoinedErrors(t, opts, errAtLeastOneOf("AlterTaskOptions.Set", "Warehouse", "UserTaskManagedInitialWarehouseSize", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParameters")) + assertOptsInvalidJoinedErrors(t, opts, errAtLeastOneOf("AlterTaskOptions.Set", "Warehouse", "UserTaskManagedInitialWarehouseSize", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParameters", "TaskAutoRetryAttempts", "UserTaskMinimumTriggerIntervalInSeconds")) }) t.Run("validation: conflicting fields for [opts.Set.Warehouse opts.Set.UserTaskManagedInitialWarehouseSize]", func(t *testing.T) { @@ -193,7 +271,7 @@ func TestTasks_Alter(t *testing.T) { t.Run("validation: at least one of the fields [opts.Unset.Warehouse opts.Unset.Schedule opts.Unset.Config opts.Unset.AllowOverlappingExecution opts.Unset.UserTaskTimeoutMs opts.Unset.SuspendTaskAfterNumFailures opts.Unset.ErrorIntegration opts.Unset.Comment opts.Unset.SessionParametersUnset] should be set", func(t *testing.T) { opts := defaultOpts() opts.Unset = &TaskUnset{} - assertOptsInvalidJoinedErrors(t, opts, errAtLeastOneOf("AlterTaskOptions.Unset", "Warehouse", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParametersUnset")) + assertOptsInvalidJoinedErrors(t, opts, errAtLeastOneOf("AlterTaskOptions.Unset", "Warehouse", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParametersUnset", "TaskAutoRetryAttempts", "UserTaskMinimumTriggerIntervalInSeconds")) }) t.Run("validation: opts.Unset.SessionParametersUnset.SessionParametersUnset should be valid", func(t *testing.T) { @@ -315,6 +393,25 @@ func TestTasks_Alter(t *testing.T) { opts.ModifyWhen = String("new when") assertOptsValidAndSQLEquals(t, opts, "ALTER TASK %s MODIFY WHEN new when", id.FullyQualifiedName()) }) + + t.Run("alter set finalize", func(t *testing.T) { + opts := defaultOpts() + finalizeId := randomSchemaObjectIdentifier() + opts.SetFinalize = &finalizeId + assertOptsValidAndSQLEquals(t, opts, "ALTER TASK %s SET FINALIZE = %s", id.FullyQualifiedName(), finalizeId.FullyQualifiedName()) + }) + + t.Run("alter unset finalize", func(t *testing.T) { + opts := defaultOpts() + opts.UnsetFinalize = Bool(true) + assertOptsValidAndSQLEquals(t, opts, "ALTER TASK %s UNSET FINALIZE", id.FullyQualifiedName()) + }) + + t.Run("alter remove when", func(t *testing.T) { + opts := defaultOpts() + opts.RemoveWhen = Bool(true) + assertOptsValidAndSQLEquals(t, opts, "ALTER TASK %s REMOVE WHEN", id.FullyQualifiedName()) + }) } func TestTasks_Drop(t *testing.T) { diff --git a/pkg/sdk/tasks_impl_gen.go b/pkg/sdk/tasks_impl_gen.go index 0a1ce9d111..9f00526c25 100644 --- a/pkg/sdk/tasks_impl_gen.go +++ b/pkg/sdk/tasks_impl_gen.go @@ -22,6 +22,11 @@ func (v *tasks) Create(ctx context.Context, request *CreateTaskRequest) error { return validateAndExec(v.client, ctx, opts) } +func (v *tasks) CreateOrAlter(ctx context.Context, request *CreateOrAlterTaskRequest) error { + opts := request.toOpts() + return validateAndExec(v.client, ctx, opts) +} + func (v *tasks) Clone(ctx context.Context, request *CloneTaskRequest) error { opts := request.toOpts() return validateAndExec(v.client, ctx, opts) @@ -48,7 +53,15 @@ func (v *tasks) Show(ctx context.Context, request *ShowTaskRequest) ([]Task, err } func (v *tasks) ShowByID(ctx context.Context, id SchemaObjectIdentifier) (*Task, error) { - return v.Describe(ctx, id) + tasks, err := v.Show(ctx, NewShowTaskRequest().WithIn(In{ + Schema: id.SchemaId(), + }).WithLike(Like{ + Pattern: String(id.Name()), + })) + if err != nil { + return nil, err + } + return collections.FindFirst(tasks, func(r Task) bool { return r.Name == id.Name() }) } func (v *tasks) Describe(ctx context.Context, id SchemaObjectIdentifier) (*Task, error) { @@ -79,8 +92,8 @@ func (v *tasks) SuspendRootTasks(ctx context.Context, taskId SchemaObjectIdentif for _, rootTask := range rootTasks { // If a root task is started, then it needs to be suspended before the child tasks can be created - if rootTask.IsStarted() { - err := v.client.Tasks.Alter(ctx, NewAlterTaskRequest(rootTask.ID()).WithSuspend(Bool(true))) + if rootTask.State == TaskStateStarted { + err := v.client.Tasks.Alter(ctx, NewAlterTaskRequest(rootTask.ID()).WithSuspend(true)) if err != nil { log.Printf("[WARN] failed to suspend task %s", rootTask.ID().FullyQualifiedName()) suspendErrs = append(suspendErrs, err) @@ -100,7 +113,7 @@ func (v *tasks) SuspendRootTasks(ctx context.Context, taskId SchemaObjectIdentif func (v *tasks) ResumeTasks(ctx context.Context, ids []SchemaObjectIdentifier) error { resumeErrs := make([]error, 0) for _, id := range ids { - err := v.client.Tasks.Alter(ctx, NewAlterTaskRequest(id).WithResume(Bool(true))) + err := v.client.Tasks.Alter(ctx, NewAlterTaskRequest(id).WithResume(true)) if err != nil { log.Printf("[WARN] failed to resume task %s", id.FullyQualifiedName()) resumeErrs = append(resumeErrs, err) @@ -148,23 +161,50 @@ func GetRootTasks(v Tasks, ctx context.Context, id SchemaObjectIdentifier) ([]Ta func (r *CreateTaskRequest) toOpts() *CreateTaskOptions { opts := &CreateTaskOptions{ - OrReplace: r.OrReplace, - IfNotExists: r.IfNotExists, - name: r.name, + OrReplace: r.OrReplace, + IfNotExists: r.IfNotExists, + name: r.name, + Schedule: r.Schedule, + Config: r.Config, + AllowOverlappingExecution: r.AllowOverlappingExecution, + SessionParameters: r.SessionParameters, + UserTaskTimeoutMs: r.UserTaskTimeoutMs, + SuspendTaskAfterNumFailures: r.SuspendTaskAfterNumFailures, + ErrorNotificationIntegration: r.ErrorNotificationIntegration, + Comment: r.Comment, + Finalize: r.Finalize, + TaskAutoRetryAttempts: r.TaskAutoRetryAttempts, + Tag: r.Tag, + UserTaskMinimumTriggerIntervalInSeconds: r.UserTaskMinimumTriggerIntervalInSeconds, + After: r.After, + When: r.When, + sql: r.sql, + } + if r.Warehouse != nil { + opts.Warehouse = &CreateTaskWarehouse{ + Warehouse: r.Warehouse.Warehouse, + UserTaskManagedInitialWarehouseSize: r.Warehouse.UserTaskManagedInitialWarehouseSize, + } + } + return opts +} - Schedule: r.Schedule, - Config: r.Config, - AllowOverlappingExecution: r.AllowOverlappingExecution, - SessionParameters: r.SessionParameters, - UserTaskTimeoutMs: r.UserTaskTimeoutMs, - SuspendTaskAfterNumFailures: r.SuspendTaskAfterNumFailures, - ErrorIntegration: r.ErrorIntegration, - CopyGrants: r.CopyGrants, - Comment: r.Comment, - After: r.After, - Tag: r.Tag, - When: r.When, - sql: r.sql, +func (r *CreateOrAlterTaskRequest) toOpts() *CreateOrAlterTaskOptions { + opts := &CreateOrAlterTaskOptions{ + name: r.name, + Schedule: r.Schedule, + Config: r.Config, + AllowOverlappingExecution: r.AllowOverlappingExecution, + UserTaskTimeoutMs: r.UserTaskTimeoutMs, + SessionParameters: r.SessionParameters, + SuspendTaskAfterNumFailures: r.SuspendTaskAfterNumFailures, + ErrorNotificationIntegration: r.ErrorNotificationIntegration, + Comment: r.Comment, + Finalize: r.Finalize, + TaskAutoRetryAttempts: r.TaskAutoRetryAttempts, + After: r.After, + When: r.When, + sql: r.sql, } if r.Warehouse != nil { opts.Warehouse = &CreateTaskWarehouse{ @@ -194,36 +234,43 @@ func (r *AlterTaskRequest) toOpts() *AlterTaskOptions { RemoveAfter: r.RemoveAfter, AddAfter: r.AddAfter, - SetTags: r.SetTags, - UnsetTags: r.UnsetTags, - ModifyAs: r.ModifyAs, - ModifyWhen: r.ModifyWhen, + SetTags: r.SetTags, + UnsetTags: r.UnsetTags, + SetFinalize: r.SetFinalize, + UnsetFinalize: r.UnsetFinalize, + ModifyAs: r.ModifyAs, + ModifyWhen: r.ModifyWhen, + RemoveWhen: r.RemoveWhen, } if r.Set != nil { opts.Set = &TaskSet{ - Warehouse: r.Set.Warehouse, - UserTaskManagedInitialWarehouseSize: r.Set.UserTaskManagedInitialWarehouseSize, - Schedule: r.Set.Schedule, - Config: r.Set.Config, - AllowOverlappingExecution: r.Set.AllowOverlappingExecution, - UserTaskTimeoutMs: r.Set.UserTaskTimeoutMs, - SuspendTaskAfterNumFailures: r.Set.SuspendTaskAfterNumFailures, - ErrorIntegration: r.Set.ErrorIntegration, - Comment: r.Set.Comment, - SessionParameters: r.Set.SessionParameters, + Warehouse: r.Set.Warehouse, + UserTaskManagedInitialWarehouseSize: r.Set.UserTaskManagedInitialWarehouseSize, + Schedule: r.Set.Schedule, + Config: r.Set.Config, + AllowOverlappingExecution: r.Set.AllowOverlappingExecution, + UserTaskTimeoutMs: r.Set.UserTaskTimeoutMs, + SuspendTaskAfterNumFailures: r.Set.SuspendTaskAfterNumFailures, + ErrorNotificationIntegration: r.Set.ErrorNotificationIntegration, + Comment: r.Set.Comment, + SessionParameters: r.Set.SessionParameters, + TaskAutoRetryAttempts: r.Set.TaskAutoRetryAttempts, + UserTaskMinimumTriggerIntervalInSeconds: r.Set.UserTaskMinimumTriggerIntervalInSeconds, } } if r.Unset != nil { opts.Unset = &TaskUnset{ - Warehouse: r.Unset.Warehouse, - Schedule: r.Unset.Schedule, - Config: r.Unset.Config, - AllowOverlappingExecution: r.Unset.AllowOverlappingExecution, - UserTaskTimeoutMs: r.Unset.UserTaskTimeoutMs, - SuspendTaskAfterNumFailures: r.Unset.SuspendTaskAfterNumFailures, - ErrorIntegration: r.Unset.ErrorIntegration, - Comment: r.Unset.Comment, - SessionParametersUnset: r.Unset.SessionParametersUnset, + Warehouse: r.Unset.Warehouse, + Schedule: r.Unset.Schedule, + Config: r.Unset.Config, + AllowOverlappingExecution: r.Unset.AllowOverlappingExecution, + UserTaskTimeoutMs: r.Unset.UserTaskTimeoutMs, + SuspendTaskAfterNumFailures: r.Unset.SuspendTaskAfterNumFailures, + ErrorIntegration: r.Unset.ErrorIntegration, + Comment: r.Unset.Comment, + TaskAutoRetryAttempts: r.Unset.TaskAutoRetryAttempts, + UserTaskMinimumTriggerIntervalInSeconds: r.Unset.UserTaskMinimumTriggerIntervalInSeconds, + SessionParametersUnset: r.Unset.SessionParametersUnset, } } return opts @@ -251,16 +298,21 @@ func (r *ShowTaskRequest) toOpts() *ShowTaskOptions { func (r taskDBRow) convert() *Task { task := Task{ - CreatedOn: r.CreatedOn, - Name: r.Name, - DatabaseName: r.DatabaseName, - SchemaName: r.SchemaName, - } - if r.Id.Valid { - task.Id = r.Id.String - } - if r.Owner.Valid { - task.Owner = r.Owner.String + CreatedOn: r.CreatedOn, + Id: r.Id, + Name: r.Name, + DatabaseName: r.DatabaseName, + SchemaName: r.SchemaName, + Owner: r.Owner, + Definition: r.Definition, + AllowOverlappingExecution: r.AllowOverlappingExecution == "true", + OwnerRoleType: r.OwnerRoleType, + } + taskRelations, err := ToTaskRelations(r.TaskRelations) + if err != nil { + log.Printf("[DEBUG] failed to convert task relations: %v", err) + } else { + task.TaskRelations = taskRelations } if r.Comment.Valid { task.Comment = r.Comment.String @@ -271,8 +323,8 @@ func (r taskDBRow) convert() *Task { if r.Schedule.Valid { task.Schedule = r.Schedule.String } - if r.Predecessors.Valid { - names, err := getPredecessors(r.Predecessors.String) + if len(r.Predecessors) > 0 { + names, err := getPredecessors(r.Predecessors) ids := make([]SchemaObjectIdentifier, len(names)) if err == nil { for i, name := range names { @@ -281,24 +333,24 @@ func (r taskDBRow) convert() *Task { } task.Predecessors = ids } - if r.State.Valid { - if strings.ToLower(r.State.String) == string(TaskStateStarted) { - task.State = TaskStateStarted + if len(r.State) > 0 { + taskState, err := ToTaskState(r.State) + if err != nil { + log.Printf("[DEBUG] failed to convert to task state: %v", err) } else { - task.State = TaskStateSuspended + task.State = taskState } } - if r.Definition.Valid { - task.Definition = r.Definition.String - } if r.Condition.Valid { task.Condition = r.Condition.String } - if r.AllowOverlappingExecution.Valid { - task.AllowOverlappingExecution = r.AllowOverlappingExecution.String == "true" - } if r.ErrorIntegration.Valid && r.ErrorIntegration.String != "null" { - task.ErrorIntegration = r.ErrorIntegration.String + id, err := ParseAccountObjectIdentifier(r.ErrorIntegration.String) + if err != nil { + log.Printf("[DEBUG] failed to parse error_integration: %v", err) + } else { + task.ErrorIntegration = &id + } } if r.LastCommittedOn.Valid { task.LastCommittedOn = r.LastCommittedOn.String @@ -306,18 +358,19 @@ func (r taskDBRow) convert() *Task { if r.LastSuspendedOn.Valid { task.LastSuspendedOn = r.LastSuspendedOn.String } - if r.OwnerRoleType.Valid { - task.OwnerRoleType = r.OwnerRoleType.String - } if r.Config.Valid { task.Config = r.Config.String } if r.Budget.Valid { task.Budget = r.Budget.String } + if r.LastSuspendedReason.Valid { + task.LastSuspendedReason = r.LastSuspendedReason.String + } return &task } +// TODO(SNOW-1348116 - next prs): Remove and use Task.TaskRelations instead func getPredecessors(predecessors string) ([]string, error) { // Since 2022_03, Snowflake returns this as a JSON array (even empty) // The list is formatted, e.g.: diff --git a/pkg/sdk/tasks_validations_gen.go b/pkg/sdk/tasks_validations_gen.go index 48197e59d3..6a5392457b 100644 --- a/pkg/sdk/tasks_validations_gen.go +++ b/pkg/sdk/tasks_validations_gen.go @@ -1,9 +1,8 @@ package sdk -import "errors" - var ( _ validatable = new(CreateTaskOptions) + _ validatable = new(CreateOrAlterTaskOptions) _ validatable = new(CloneTaskOptions) _ validatable = new(AlterTaskOptions) _ validatable = new(DropTaskOptions) @@ -14,31 +13,58 @@ var ( func (opts *CreateTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error + if valueSet(opts.SessionParameters) { + if err := opts.SessionParameters.validate(); err != nil { + errs = append(errs, err) + } + } + if valueSet(opts.Warehouse) { + if !exactlyOneValueSet(opts.Warehouse.Warehouse, opts.Warehouse.UserTaskManagedInitialWarehouseSize) { + errs = append(errs, errExactlyOneOf("CreateTaskOptions.Warehouse", "Warehouse", "UserTaskManagedInitialWarehouseSize")) + } + } if !ValidObjectIdentifier(opts.name) { errs = append(errs, ErrInvalidObjectIdentifier) } if everyValueSet(opts.OrReplace, opts.IfNotExists) { errs = append(errs, errOneOf("CreateTaskOptions", "OrReplace", "IfNotExists")) } - if valueSet(opts.Warehouse) { - if ok := exactlyOneValueSet(opts.Warehouse.Warehouse, opts.Warehouse.UserTaskManagedInitialWarehouseSize); !ok { - errs = append(errs, errExactlyOneOf("CreateTaskOptions.Warehouse", "Warehouse", "UserTaskManagedInitialWarehouseSize")) - } + if opts.ErrorNotificationIntegration != nil && !ValidObjectIdentifier(opts.ErrorNotificationIntegration) { + errs = append(errs, errInvalidIdentifier("CreateTaskOptions", "ErrorNotificationIntegration")) + } + return JoinErrors(errs...) +} + +func (opts *CreateOrAlterTaskOptions) validate() error { + if opts == nil { + return ErrNilOptions } + var errs []error if valueSet(opts.SessionParameters) { if err := opts.SessionParameters.validate(); err != nil { errs = append(errs, err) } } - return errors.Join(errs...) + if valueSet(opts.Warehouse) { + if !exactlyOneValueSet(opts.Warehouse.Warehouse, opts.Warehouse.UserTaskManagedInitialWarehouseSize) { + errs = append(errs, errExactlyOneOf("CreateOrAlterTaskOptions.CreateTaskWarehouse", "Warehouse", "UserTaskManagedInitialWarehouseSize")) + } + } + if !ValidObjectIdentifier(opts.name) { + errs = append(errs, ErrInvalidObjectIdentifier) + } + if opts.ErrorNotificationIntegration != nil && !ValidObjectIdentifier(opts.ErrorNotificationIntegration) { + errs = append(errs, errInvalidIdentifier("CreateOrAlterTaskOptions", "ErrorNotificationIntegration")) + } + return JoinErrors(errs...) } func (opts *CloneTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error if !ValidObjectIdentifier(opts.name) { @@ -47,36 +73,39 @@ func (opts *CloneTaskOptions) validate() error { if !ValidObjectIdentifier(opts.sourceTask) { errs = append(errs, ErrInvalidObjectIdentifier) } - return errors.Join(errs...) + return JoinErrors(errs...) } func (opts *AlterTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error if !ValidObjectIdentifier(opts.name) { errs = append(errs, ErrInvalidObjectIdentifier) } - if ok := exactlyOneValueSet(opts.Resume, opts.Suspend, opts.RemoveAfter, opts.AddAfter, opts.Set, opts.Unset, opts.SetTags, opts.UnsetTags, opts.ModifyAs, opts.ModifyWhen); !ok { - errs = append(errs, errExactlyOneOf("AlterTaskOptions", "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "ModifyAs", "ModifyWhen")) + if !exactlyOneValueSet(opts.Resume, opts.Suspend, opts.RemoveAfter, opts.AddAfter, opts.Set, opts.Unset, opts.SetTags, opts.UnsetTags, opts.SetFinalize, opts.UnsetFinalize, opts.ModifyAs, opts.ModifyWhen, opts.RemoveWhen) { + errs = append(errs, errExactlyOneOf("AlterTaskOptions", "Resume", "Suspend", "RemoveAfter", "AddAfter", "Set", "Unset", "SetTags", "UnsetTags", "SetFinalize", "UnsetFinalize", "ModifyAs", "ModifyWhen", "RemoveWhen")) } if valueSet(opts.Set) { - if ok := anyValueSet(opts.Set.Warehouse, opts.Set.UserTaskManagedInitialWarehouseSize, opts.Set.Schedule, opts.Set.Config, opts.Set.AllowOverlappingExecution, opts.Set.UserTaskTimeoutMs, opts.Set.SuspendTaskAfterNumFailures, opts.Set.ErrorIntegration, opts.Set.Comment, opts.Set.SessionParameters); !ok { - errs = append(errs, errAtLeastOneOf("AlterTaskOptions.Set", "Warehouse", "UserTaskManagedInitialWarehouseSize", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParameters")) - } - if everyValueSet(opts.Set.Warehouse, opts.Set.UserTaskManagedInitialWarehouseSize) { - errs = append(errs, errOneOf("AlterTaskOptions.Set", "Warehouse", "UserTaskManagedInitialWarehouseSize")) - } if valueSet(opts.Set.SessionParameters) { if err := opts.Set.SessionParameters.validate(); err != nil { errs = append(errs, err) } } + if !anyValueSet(opts.Set.Warehouse, opts.Set.UserTaskManagedInitialWarehouseSize, opts.Set.Schedule, opts.Set.Config, opts.Set.AllowOverlappingExecution, opts.Set.UserTaskTimeoutMs, opts.Set.SuspendTaskAfterNumFailures, opts.Set.ErrorNotificationIntegration, opts.Set.Comment, opts.Set.SessionParameters, opts.Set.TaskAutoRetryAttempts, opts.Set.UserTaskMinimumTriggerIntervalInSeconds) { + errs = append(errs, errAtLeastOneOf("AlterTaskOptions.Set", "Warehouse", "UserTaskManagedInitialWarehouseSize", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParameters", "TaskAutoRetryAttempts", "UserTaskMinimumTriggerIntervalInSeconds")) + } + if everyValueSet(opts.Set.Warehouse, opts.Set.UserTaskManagedInitialWarehouseSize) { + errs = append(errs, errOneOf("AlterTaskOptions.Set", "Warehouse", "UserTaskManagedInitialWarehouseSize")) + } + if opts.Set.ErrorNotificationIntegration != nil && !ValidObjectIdentifier(opts.Set.ErrorNotificationIntegration) { + errs = append(errs, errInvalidIdentifier("AlterTaskOptions.Set", "ErrorNotificationIntegration")) + } } if valueSet(opts.Unset) { - if ok := anyValueSet(opts.Unset.Warehouse, opts.Unset.Schedule, opts.Unset.Config, opts.Unset.AllowOverlappingExecution, opts.Unset.UserTaskTimeoutMs, opts.Unset.SuspendTaskAfterNumFailures, opts.Unset.ErrorIntegration, opts.Unset.Comment, opts.Unset.SessionParametersUnset); !ok { - errs = append(errs, errAtLeastOneOf("AlterTaskOptions.Unset", "Warehouse", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParametersUnset")) + if !anyValueSet(opts.Unset.Warehouse, opts.Unset.Schedule, opts.Unset.Config, opts.Unset.AllowOverlappingExecution, opts.Unset.UserTaskTimeoutMs, opts.Unset.SuspendTaskAfterNumFailures, opts.Unset.ErrorIntegration, opts.Unset.Comment, opts.Unset.SessionParametersUnset, opts.Unset.TaskAutoRetryAttempts, opts.Unset.UserTaskMinimumTriggerIntervalInSeconds) { + errs = append(errs, errAtLeastOneOf("AlterTaskOptions.Unset", "Warehouse", "Schedule", "Config", "AllowOverlappingExecution", "UserTaskTimeoutMs", "SuspendTaskAfterNumFailures", "ErrorIntegration", "Comment", "SessionParametersUnset", "TaskAutoRetryAttempts", "UserTaskMinimumTriggerIntervalInSeconds")) } if valueSet(opts.Unset.SessionParametersUnset) { if err := opts.Unset.SessionParametersUnset.validate(); err != nil { @@ -84,46 +113,46 @@ func (opts *AlterTaskOptions) validate() error { } } } - return errors.Join(errs...) + return JoinErrors(errs...) } func (opts *DropTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error if !ValidObjectIdentifier(opts.name) { errs = append(errs, ErrInvalidObjectIdentifier) } - return errors.Join(errs...) + return JoinErrors(errs...) } func (opts *ShowTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error - return errors.Join(errs...) + return JoinErrors(errs...) } func (opts *DescribeTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error if !ValidObjectIdentifier(opts.name) { errs = append(errs, ErrInvalidObjectIdentifier) } - return errors.Join(errs...) + return JoinErrors(errs...) } func (opts *ExecuteTaskOptions) validate() error { if opts == nil { - return errors.Join(ErrNilOptions) + return ErrNilOptions } var errs []error if !ValidObjectIdentifier(opts.name) { errs = append(errs, ErrInvalidObjectIdentifier) } - return errors.Join(errs...) + return JoinErrors(errs...) } diff --git a/pkg/sdk/testint/grants_integration_test.go b/pkg/sdk/testint/grants_integration_test.go index f4acd68643..1fee524fa5 100644 --- a/pkg/sdk/testint/grants_integration_test.go +++ b/pkg/sdk/testint/grants_integration_test.go @@ -1654,10 +1654,10 @@ func TestInt_GrantOwnership(t *testing.T) { }) t.Run("on task - with ownership", func(t *testing.T) { - task, taskCleanup := testClientHelper().Task.CreateTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) t.Cleanup(taskCleanup) - err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(sdk.Bool(true))) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(true)) require.NoError(t, err) role, roleCleanup := testClientHelper().Role.CreateRole(t) @@ -1699,14 +1699,14 @@ func TestInt_GrantOwnership(t *testing.T) { // Use a previously prepared role to create a task usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) - task, taskCleanup := testClientHelper().Task.CreateTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) t.Cleanup(func() { usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) defer usePreviousRole() taskCleanup() }) - err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(sdk.Bool(true))) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(true)) require.NoError(t, err) usePreviousRole() @@ -1745,7 +1745,7 @@ func TestInt_GrantOwnership(t *testing.T) { // Use a previously prepared role to create a task usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) - task, taskCleanup := testClientHelper().Task.CreateTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) t.Cleanup(taskCleanup) err := client.Grants.GrantPrivilegesToAccountRole( @@ -1766,7 +1766,7 @@ func TestInt_GrantOwnership(t *testing.T) { ) require.NoError(t, err) - err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(sdk.Bool(true))) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(true)) require.NoError(t, err) usePreviousRole() @@ -1801,16 +1801,16 @@ func TestInt_GrantOwnership(t *testing.T) { }) t.Run("on all tasks - with ownership", func(t *testing.T) { - task, taskCleanup := testClientHelper().Task.CreateTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) t.Cleanup(taskCleanup) - err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(sdk.Bool(true))) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(true)) require.NoError(t, err) - secondTask, secondTaskCleanup := testClientHelper().Task.CreateTask(t) + secondTask, secondTaskCleanup := testClientHelper().Task.Create(t) t.Cleanup(secondTaskCleanup) - err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(secondTask.ID()).WithResume(sdk.Bool(true))) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(secondTask.ID()).WithResume(true)) require.NoError(t, err) role, roleCleanup := testClientHelper().Role.CreateRole(t) @@ -1873,10 +1873,10 @@ func TestInt_GrantOwnership(t *testing.T) { // Use a previously prepared role to create a task usePreviousRole := testClientHelper().Role.UseRole(t, taskRole.ID()) - task, taskCleanup := testClientHelper().Task.CreateTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) t.Cleanup(taskCleanup) - secondTask, secondTaskCleanup := testClientHelper().Task.CreateTaskWithAfter(t, task.ID()) + secondTask, secondTaskCleanup := testClientHelper().Task.CreateWithAfter(t, task.ID()) t.Cleanup(secondTaskCleanup) err := client.Grants.GrantPrivilegesToAccountRole( @@ -1917,10 +1917,10 @@ func TestInt_GrantOwnership(t *testing.T) { usePreviousRole() - err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(secondTask.ID()).WithResume(sdk.Bool(true))) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(secondTask.ID()).WithResume(true)) require.NoError(t, err) - err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(sdk.Bool(true))) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithResume(true)) require.NoError(t, err) t.Cleanup(func() { diff --git a/pkg/sdk/testint/tasks_gen_integration_test.go b/pkg/sdk/testint/tasks_gen_integration_test.go index 984f1f80ea..23ec833cd4 100644 --- a/pkg/sdk/testint/tasks_gen_integration_test.go +++ b/pkg/sdk/testint/tasks_gen_integration_test.go @@ -1,8 +1,15 @@ package testint import ( - "errors" + "fmt" "testing" + "time" + + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert/objectparametersassert" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/helpers/random" + + assertions "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert" + "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/acceptance/bettertestspoc/assert/objectassert" "github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk" "github.com/stretchr/testify/assert" @@ -12,208 +19,244 @@ import ( func TestInt_Tasks(t *testing.T) { client := testClient(t) ctx := testContext(t) - sql := "SELECT CURRENT_TIMESTAMP" - assertTask := func(t *testing.T, task *sdk.Task, id sdk.SchemaObjectIdentifier) { + // TODO [SNOW-1017580]: replace with real value + const gcpPubsubSubscriptionName = "projects/project-1234/subscriptions/sub2" + errorIntegrationId := testClientHelper().Ids.RandomAccountObjectIdentifier() + err := client.NotificationIntegrations.Create(ctx, + sdk.NewCreateNotificationIntegrationRequest(errorIntegrationId, true). + WithAutomatedDataLoadsParams(sdk.NewAutomatedDataLoadsParamsRequest(). + WithGoogleAutoParams(sdk.NewGoogleAutoParamsRequest(gcpPubsubSubscriptionName)), + ), + ) + require.NoError(t, err) + t.Cleanup(func() { + require.NoError(t, client.NotificationIntegrations.Drop(ctx, sdk.NewDropNotificationIntegrationRequest(errorIntegrationId).WithIfExists(sdk.Bool(true)))) + }) + + assertTask := func(t *testing.T, task *sdk.Task, id sdk.SchemaObjectIdentifier, warehouseName string) { t.Helper() - assert.Equal(t, id, task.ID()) - assert.NotEmpty(t, task.CreatedOn) - assert.Equal(t, id.Name(), task.Name) - assert.NotEmpty(t, task.Id) - assert.Equal(t, testClientHelper().Ids.DatabaseId().Name(), task.DatabaseName) - assert.Equal(t, testClientHelper().Ids.SchemaId().Name(), task.SchemaName) - assert.Equal(t, "ACCOUNTADMIN", task.Owner) - assert.Equal(t, "", task.Comment) - assert.Equal(t, "", task.Warehouse) - assert.Equal(t, "", task.Schedule) - assert.Empty(t, task.Predecessors) - assert.Equal(t, sdk.TaskStateSuspended, task.State) - assert.Equal(t, sql, task.Definition) - assert.Equal(t, "", task.Condition) - assert.Equal(t, false, task.AllowOverlappingExecution) - assert.Empty(t, task.ErrorIntegration) - assert.Empty(t, task.LastCommittedOn) - assert.Empty(t, task.LastSuspendedOn) - assert.Equal(t, "ROLE", task.OwnerRoleType) - assert.Empty(t, task.Config) - assert.Empty(t, task.Budget) + assertions.AssertThat(t, objectassert.TaskFromObject(t, task). + HasNotEmptyCreatedOn(). + HasName(id.Name()). + HasNotEmptyId(). + HasDatabaseName(testClientHelper().Ids.DatabaseId().Name()). + HasSchemaName(testClientHelper().Ids.SchemaId().Name()). + HasOwner("ACCOUNTADMIN"). + HasComment(""). + HasWarehouse(warehouseName). + HasSchedule(""). + HasPredecessors(). + HasState(sdk.TaskStateStarted). + HasDefinition(sql). + HasCondition(""). + HasAllowOverlappingExecution(false). + HasErrorIntegration(nil). + HasLastCommittedOn(""). + HasLastSuspendedOn(""). + HasOwnerRoleType("ROLE"). + HasConfig(""). + HasBudget(""). + HasLastSuspendedOn(""). + HasTaskRelations(sdk.TaskRelations{}), + ) } - assertTaskWithOptions := func(t *testing.T, task *sdk.Task, id sdk.SchemaObjectIdentifier, comment string, warehouse string, schedule string, condition string, allowOverlappingExecution bool, config string, predecessor *sdk.SchemaObjectIdentifier) { + assertTaskWithOptions := func(t *testing.T, task *sdk.Task, id sdk.SchemaObjectIdentifier, comment string, warehouse string, schedule string, condition string, allowOverlappingExecution bool, config string, predecessor *sdk.SchemaObjectIdentifier, errorIntegrationName *sdk.AccountObjectIdentifier) { t.Helper() - assert.Equal(t, id, task.ID()) - assert.NotEmpty(t, task.CreatedOn) - assert.Equal(t, id.Name(), task.Name) - assert.NotEmpty(t, task.Id) - assert.Equal(t, testClientHelper().Ids.DatabaseId().Name(), task.DatabaseName) - assert.Equal(t, testClientHelper().Ids.SchemaId().Name(), task.SchemaName) - assert.Equal(t, "ACCOUNTADMIN", task.Owner) - assert.Equal(t, comment, task.Comment) - assert.Equal(t, warehouse, task.Warehouse) - assert.Equal(t, schedule, task.Schedule) - assert.Equal(t, sdk.TaskStateSuspended, task.State) - assert.Equal(t, sql, task.Definition) - assert.Equal(t, condition, task.Condition) - assert.Equal(t, allowOverlappingExecution, task.AllowOverlappingExecution) - assert.Empty(t, task.ErrorIntegration) - assert.Empty(t, task.LastCommittedOn) - assert.Empty(t, task.LastSuspendedOn) - assert.Equal(t, "ROLE", task.OwnerRoleType) - assert.Equal(t, config, task.Config) - assert.Empty(t, task.Budget) + + asserts := objectassert.TaskFromObject(t, task). + HasNotEmptyCreatedOn(). + HasName(id.Name()). + HasNotEmptyId(). + HasDatabaseName(testClientHelper().Ids.DatabaseId().Name()). + HasSchemaName(testClientHelper().Ids.SchemaId().Name()). + HasOwner("ACCOUNTADMIN"). + HasComment(comment). + HasWarehouse(warehouse). + HasSchedule(schedule). + HasState(sdk.TaskStateSuspended). + HasDefinition(sql). + HasCondition(condition). + HasAllowOverlappingExecution(allowOverlappingExecution). + HasErrorIntegration(errorIntegrationName). + HasLastCommittedOn(""). + HasLastSuspendedOn(""). + HasOwnerRoleType("ROLE"). + HasConfig(config). + HasBudget(""). + HasLastSuspendedOn("") + if predecessor != nil { - assert.Len(t, task.Predecessors, 1) - assert.Contains(t, task.Predecessors, *predecessor) + asserts.HasPredecessors(*predecessor) + asserts.HasTaskRelations(sdk.TaskRelations{ + Predecessors: []sdk.SchemaObjectIdentifier{*predecessor}, + }) } else { - assert.Empty(t, task.Predecessors) + asserts.HasPredecessors() + asserts.HasTaskRelations(sdk.TaskRelations{}) } + + assertions.AssertThat(t, asserts) } assertTaskTerse := func(t *testing.T, task *sdk.Task, id sdk.SchemaObjectIdentifier, schedule string) { t.Helper() - assert.Equal(t, id, task.ID()) - assert.NotEmpty(t, task.CreatedOn) - assert.Equal(t, id.Name(), task.Name) - assert.Equal(t, testClientHelper().Ids.DatabaseId().Name(), task.DatabaseName) - assert.Equal(t, testClientHelper().Ids.SchemaId().Name(), task.SchemaName) - assert.Equal(t, schedule, task.Schedule) - - // all below are not contained in the terse response, that's why all of them we expect to be empty - assert.Empty(t, task.Id) - assert.Empty(t, task.Owner) - assert.Empty(t, task.Comment) - assert.Empty(t, task.Warehouse) - assert.Empty(t, task.Predecessors) - assert.Empty(t, task.State) - assert.Empty(t, task.Definition) - assert.Empty(t, task.Condition) - assert.Empty(t, task.AllowOverlappingExecution) - assert.Empty(t, task.ErrorIntegration) - assert.Empty(t, task.LastCommittedOn) - assert.Empty(t, task.LastSuspendedOn) - assert.Empty(t, task.OwnerRoleType) - assert.Empty(t, task.Config) - assert.Empty(t, task.Budget) + assertions.AssertThat(t, objectassert.TaskFromObject(t, task). + HasNotEmptyCreatedOn(). + HasName(id.Name()). + HasDatabaseName(testClientHelper().Ids.DatabaseId().Name()). + HasSchemaName(testClientHelper().Ids.SchemaId().Name()). + HasSchedule(schedule). + // all below are not contained in the terse response, that's why all of them we expect to be empty + HasId(""). + HasOwner(""). + HasComment(""). + HasWarehouse(""). + HasPredecessors(). + HasState(""). + HasDefinition(""). + HasCondition(""). + HasAllowOverlappingExecution(false). + HasErrorIntegration(nil). + HasLastCommittedOn(""). + HasLastSuspendedOn(""). + HasOwnerRoleType(""). + HasConfig(""). + HasBudget(""). + HasLastSuspendedOn(""). + HasTaskRelations(sdk.TaskRelations{}), + ) } - cleanupTaskProvider := func(id sdk.SchemaObjectIdentifier) func() { - return func() { - err := client.Tasks.Drop(ctx, sdk.NewDropTaskRequest(id)) - require.NoError(t, err) - } - } - - createTaskBasicRequest := func(t *testing.T) *sdk.CreateTaskRequest { - t.Helper() + t.Run("create task: no optionals", func(t *testing.T) { id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - return sdk.NewCreateTaskRequest(id, sql) - } - - createTaskWithRequest := func(t *testing.T, request *sdk.CreateTaskRequest) *sdk.Task { - t.Helper() - id := request.GetName() - - err := client.Tasks.Create(ctx, request) + err := testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, sql)) require.NoError(t, err) - t.Cleanup(cleanupTaskProvider(id)) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) - task, err := client.Tasks.ShowByID(ctx, id) + task, err := testClientHelper().Task.Show(t, id) require.NoError(t, err) - return task - } - - createTask := func(t *testing.T) *sdk.Task { - t.Helper() - return createTaskWithRequest(t, createTaskBasicRequest(t)) - } - - t.Run("create task: no optionals", func(t *testing.T) { - request := createTaskBasicRequest(t) - - task := createTaskWithRequest(t, request) - - assertTask(t, task, request.GetName()) + assertTask(t, task, id, "") }) t.Run("create task: with initial warehouse", func(t *testing.T) { - request := createTaskBasicRequest(t). - WithWarehouse(sdk.NewCreateTaskWarehouseRequest().WithUserTaskManagedInitialWarehouseSize(sdk.Pointer(sdk.WarehouseSizeXSmall))) + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - task := createTaskWithRequest(t, request) + err := testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, sql).WithWarehouse(*sdk.NewCreateTaskWarehouseRequest().WithUserTaskManagedInitialWarehouseSize(sdk.WarehouseSizeXSmall))) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) + + task, err := testClientHelper().Task.Show(t, id) + require.NoError(t, err) - assertTask(t, task, request.GetName()) + assertions.AssertThat(t, objectparametersassert.TaskParameters(t, task.ID()). + HasUserTaskManagedInitialWarehouseSize(sdk.WarehouseSizeXSmall), + ) + + assertTask(t, task, id, "") }) - t.Run("create task: almost complete case", func(t *testing.T) { - request := createTaskBasicRequest(t). - WithOrReplace(sdk.Bool(true)). - WithWarehouse(sdk.NewCreateTaskWarehouseRequest().WithWarehouse(sdk.Pointer(testClientHelper().Ids.WarehouseId()))). - WithSchedule(sdk.String("10 MINUTE")). - WithConfig(sdk.String(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`)). - WithAllowOverlappingExecution(sdk.Bool(true)). - WithSessionParameters(&sdk.SessionParameters{ + t.Run("create task: complete case", func(t *testing.T) { + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + + err = testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, sql). + WithOrReplace(true). + WithWarehouse(*sdk.NewCreateTaskWarehouseRequest().WithWarehouse(testClientHelper().Ids.WarehouseId())). + WithErrorNotificationIntegration(errorIntegrationId). + WithSchedule("10 MINUTE"). + WithConfig(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`). + WithAllowOverlappingExecution(true). + WithSessionParameters(sdk.SessionParameters{ JSONIndent: sdk.Int(4), }). - WithUserTaskTimeoutMs(sdk.Int(500)). - WithSuspendTaskAfterNumFailures(sdk.Int(3)). - WithComment(sdk.String("some comment")). - WithWhen(sdk.String(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`)) - id := request.GetName() + WithUserTaskTimeoutMs(500). + WithSuspendTaskAfterNumFailures(3). + WithComment("some comment"). + WithWhen(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`)) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) - task := createTaskWithRequest(t, request) + task, err := testClientHelper().Task.Show(t, id) + require.NoError(t, err) - assertTaskWithOptions(t, task, id, "some comment", testClientHelper().Ids.WarehouseId().Name(), "10 MINUTE", `SYSTEM$STREAM_HAS_DATA('MYSTREAM')`, true, `{"output_dir": "/temp/test_directory/", "learning_rate": 0.1}`, nil) + assertTaskWithOptions(t, task, id, "some comment", testClientHelper().Ids.WarehouseId().Name(), "10 MINUTE", `SYSTEM$STREAM_HAS_DATA('MYSTREAM')`, true, `{"output_dir": "/temp/test_directory/", "learning_rate": 0.1}`, nil, &errorIntegrationId) }) t.Run("create task: with after", func(t *testing.T) { - otherId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - - request := sdk.NewCreateTaskRequest(otherId, sql).WithSchedule(sdk.String("10 MINUTE")) + rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - createTaskWithRequest(t, request) + err := testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(rootTaskId, sql)) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, rootTaskId)) - request = createTaskBasicRequest(t). - WithAfter([]sdk.SchemaObjectIdentifier{otherId}) + err = testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTaskId})) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) - task := createTaskWithRequest(t, request) + task, err := testClientHelper().Task.Show(t, id) + require.NoError(t, err) - assertTaskWithOptions(t, task, request.GetName(), "", "", "", "", false, "", &otherId) + assertTaskWithOptions(t, task, id, "", "", "", "", false, "", &rootTaskId, nil) }) - t.Run("create dag of tasks", func(t *testing.T) { - rootId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + t.Run("create task: with after and finalizer", func(t *testing.T) { + rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + finalizerId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - request := sdk.NewCreateTaskRequest(rootId, sql).WithSchedule(sdk.String("10 MINUTE")) - root := createTaskWithRequest(t, request) + err := testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(rootTaskId, sql)) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, rootTaskId)) - require.Empty(t, root.Predecessors) + err = testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTaskId})) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) - t1Id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + err = testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(finalizerId, sql).WithFinalize(rootTaskId)) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, finalizerId)) - request = sdk.NewCreateTaskRequest(t1Id, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootId}) - t1 := createTaskWithRequest(t, request) + assertions.AssertThat(t, objectassert.Task(t, rootTaskId). + HasTaskRelations(sdk.TaskRelations{ + Predecessors: []sdk.SchemaObjectIdentifier{}, + FinalizerTask: &finalizerId, + }), + ) + }) - require.Equal(t, []sdk.SchemaObjectIdentifier{rootId}, t1.Predecessors) + // Tested graph + // t1 + // / \ + // root t3 + // \ / + // t2 + t.Run("create dag of tasks", func(t *testing.T) { + rootId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + root, rootCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(rootId, sql).WithSchedule("10 MINUTE")) + t.Cleanup(rootCleanup) + require.Empty(t, root.Predecessors) - t2Id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + t1, t1Cleanup := testClientHelper().Task.CreateWithAfter(t, rootId) + t.Cleanup(t1Cleanup) + require.Equal(t, []sdk.SchemaObjectIdentifier{rootId}, t1.Predecessors) - request = sdk.NewCreateTaskRequest(t2Id, sql).WithAfter([]sdk.SchemaObjectIdentifier{t1Id, rootId}) - t2 := createTaskWithRequest(t, request) + t2, t2Cleanup := testClientHelper().Task.CreateWithAfter(t, t1.ID(), rootId) + t.Cleanup(t2Cleanup) require.Contains(t, t2.Predecessors, rootId) - require.Contains(t, t2.Predecessors, t1Id) + require.Contains(t, t2.Predecessors, t1.ID()) require.Len(t, t2.Predecessors, 2) - t3Id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + t3, t3Cleanup := testClientHelper().Task.CreateWithAfter(t, t2.ID(), t1.ID()) + t.Cleanup(t3Cleanup) - request = sdk.NewCreateTaskRequest(t3Id, sql).WithAfter([]sdk.SchemaObjectIdentifier{t2Id, t1Id}) - t3 := createTaskWithRequest(t, request) - - require.Contains(t, t3.Predecessors, t2Id) - require.Contains(t, t3.Predecessors, t1Id) + require.Contains(t, t3.Predecessors, t2.ID()) + require.Contains(t, t3.Predecessors, t1.ID()) require.Len(t, t3.Predecessors, 2) rootTasks, err := sdk.GetRootTasks(client.Tasks, ctx, rootId) @@ -221,115 +264,114 @@ func TestInt_Tasks(t *testing.T) { require.Len(t, rootTasks, 1) require.Equal(t, rootId, rootTasks[0].ID()) - rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t1Id) + rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t1.ID()) require.NoError(t, err) require.Len(t, rootTasks, 1) require.Equal(t, rootId, rootTasks[0].ID()) - rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t2Id) + rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t2.ID()) require.NoError(t, err) require.Len(t, rootTasks, 1) require.Equal(t, rootId, rootTasks[0].ID()) - rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t3Id) + rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t3.ID()) require.NoError(t, err) require.Len(t, rootTasks, 1) require.Equal(t, rootId, rootTasks[0].ID()) // cannot set ALLOW_OVERLAPPING_EXECUTION on child task - alterRequest := sdk.NewAlterTaskRequest(t1Id).WithSet(sdk.NewTaskSetRequest().WithAllowOverlappingExecution(sdk.Bool(true))) + alterRequest := sdk.NewAlterTaskRequest(t1.ID()).WithSet(*sdk.NewTaskSetRequest().WithAllowOverlappingExecution(true)) err = client.Tasks.Alter(ctx, alterRequest) require.ErrorContains(t, err, "Cannot set allow_overlapping_execution on non-root task") // can set ALLOW_OVERLAPPING_EXECUTION on root task - alterRequest = sdk.NewAlterTaskRequest(rootId).WithSet(sdk.NewTaskSetRequest().WithAllowOverlappingExecution(sdk.Bool(true))) + alterRequest = sdk.NewAlterTaskRequest(rootId).WithSet(*sdk.NewTaskSetRequest().WithAllowOverlappingExecution(true)) err = client.Tasks.Alter(ctx, alterRequest) require.NoError(t, err) // can create cycle, because DAG is suspended - alterRequest = sdk.NewAlterTaskRequest(t1Id).WithAddAfter([]sdk.SchemaObjectIdentifier{t3Id}) + alterRequest = sdk.NewAlterTaskRequest(t1.ID()).WithAddAfter([]sdk.SchemaObjectIdentifier{t3.ID()}) err = client.Tasks.Alter(ctx, alterRequest) require.NoError(t, err) // can get the root task even with cycle - rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t3Id) + rootTasks, err = sdk.GetRootTasks(client.Tasks, ctx, t3.ID()) require.NoError(t, err) require.Len(t, rootTasks, 1) require.Equal(t, rootId, rootTasks[0].ID()) // we get an error when trying to start - alterRequest = sdk.NewAlterTaskRequest(rootId).WithResume(sdk.Bool(true)) + alterRequest = sdk.NewAlterTaskRequest(rootId).WithResume(true) err = client.Tasks.Alter(ctx, alterRequest) require.ErrorContains(t, err, "Graph has at least one cycle containing task") }) + // Tested graph + // root1 + // \ + // t1 + // / + // root2 t.Run("create dag of tasks - multiple roots", func(t *testing.T) { root1Id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - - request := sdk.NewCreateTaskRequest(root1Id, sql).WithSchedule(sdk.String("10 MINUTE")) - root1 := createTaskWithRequest(t, request) - + root1, root1Cleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(root1Id, sql).WithSchedule("10 MINUTE")) + t.Cleanup(root1Cleanup) require.Empty(t, root1.Predecessors) root2Id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - - request = sdk.NewCreateTaskRequest(root2Id, sql).WithSchedule(sdk.String("10 MINUTE")) - root2 := createTaskWithRequest(t, request) - + root2, root2Cleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(root2Id, sql).WithSchedule("10 MINUTE")) + t.Cleanup(root2Cleanup) require.Empty(t, root2.Predecessors) - t1Id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - - request = sdk.NewCreateTaskRequest(t1Id, sql).WithAfter([]sdk.SchemaObjectIdentifier{root1Id, root2Id}) - t1 := createTaskWithRequest(t, request) + t1, t1Cleanup := testClientHelper().Task.CreateWithAfter(t, root1.ID(), root2.ID()) + t.Cleanup(t1Cleanup) require.Contains(t, t1.Predecessors, root1Id) require.Contains(t, t1.Predecessors, root2Id) require.Len(t, t1.Predecessors, 2) - rootTasks, err := sdk.GetRootTasks(client.Tasks, ctx, t1Id) + rootTasks, err := sdk.GetRootTasks(client.Tasks, ctx, t1.ID()) require.NoError(t, err) require.Len(t, rootTasks, 2) require.Contains(t, []sdk.SchemaObjectIdentifier{root1Id, root2Id}, rootTasks[0].ID()) require.Contains(t, []sdk.SchemaObjectIdentifier{root1Id, root2Id}, rootTasks[1].ID()) // we get an error when trying to start - alterRequest := sdk.NewAlterTaskRequest(root1Id).WithResume(sdk.Bool(true)) - err = client.Tasks.Alter(ctx, alterRequest) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(root1Id).WithResume(true)) require.ErrorContains(t, err, "The graph has more than one root task (one without predecessors)") }) - // TODO: this fails with `syntax error line 1 at position 89 unexpected 'GRANTS'`. - // The reason is that in the documentation there is a note: "This parameter is not supported currently.". - // t.Run("create task: with grants", func(t *testing.T) { - // name := randomString(t) - // id := NewSchemaObjectIdentifier(database.Name, schema.Name, name) - // - // request := NewCreateTaskRequest(id, sql). - // WithOrReplace(Bool(true)). - // WithCopyGrants(Bool(true)) - // - // err := client.Tasks.Create(ctx, request) - // require.NoError(t, err) - // t.Cleanup(cleanupTaskProvider(id)) - // - // task, err := client.Tasks.ShowByID(ctx, id) - // - // require.NoError(t, err) - // assertTaskWithOptions(t, task, id, name, "", "", "", "", false, "", nil) - // }) + t.Run("validate: finalizer set on non-root task", func(t *testing.T) { + rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + finalizerId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + + err := testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(rootTaskId, sql)) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, rootTaskId)) + + err = testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTaskId})) + require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) + + err = testClient(t).Tasks.Create(ctx, sdk.NewCreateTaskRequest(finalizerId, sql).WithFinalize(id)) + require.ErrorContains(t, err, "cannot finalize a non-root task") + }) t.Run("create task: with tags", func(t *testing.T) { tag, tagCleanup := testClientHelper().Tag.CreateTag(t) t.Cleanup(tagCleanup) - request := createTaskBasicRequest(t). - WithTag([]sdk.TagAssociation{{ - Name: tag.ID(), - Value: "v1", - }}) - - task := createTaskWithRequest(t, request) + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + task, taskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(id, sql). + WithTag([]sdk.TagAssociation{ + { + Name: tag.ID(), + Value: "v1", + }, + }), + ) + t.Cleanup(taskCleanup) returnedTagValue, err := client.SystemFunctions.GetTag(ctx, tag.ID(), task.ID(), sdk.ObjectTypeTask) require.NoError(t, err) @@ -338,111 +380,216 @@ func TestInt_Tasks(t *testing.T) { }) t.Run("clone task: default", func(t *testing.T) { - sourceTask := createTask(t) + rootTask, rootTaskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(rootTaskCleanup) + + sourceTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + sourceTask, taskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(sourceTaskId, sql). + WithAfter([]sdk.SchemaObjectIdentifier{rootTask.ID()}). + WithAllowOverlappingExecution(false). + WithWarehouse(*sdk.NewCreateTaskWarehouseRequest().WithWarehouse(testClientHelper().Ids.WarehouseId())). + WithComment(random.Comment()). + WithWhen(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`), + ) + t.Cleanup(taskCleanup) id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - - request := sdk.NewCloneTaskRequest(id, sourceTask.ID()) - - err := client.Tasks.Clone(ctx, request) + err := client.Tasks.Clone(ctx, sdk.NewCloneTaskRequest(id, sourceTask.ID())) require.NoError(t, err) - t.Cleanup(cleanupTaskProvider(id)) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) task, err := client.Tasks.ShowByID(ctx, id) require.NoError(t, err) - assertTask(t, task, request.GetName()) + assert.Equal(t, sourceTask.Definition, task.Definition) + assert.Equal(t, sourceTask.Config, task.Config) + assert.Equal(t, sourceTask.Condition, task.Condition) + assert.Equal(t, sourceTask.Warehouse, task.Warehouse) + assert.Equal(t, sourceTask.Predecessors, task.Predecessors) + assert.Equal(t, sourceTask.AllowOverlappingExecution, task.AllowOverlappingExecution) + assert.Equal(t, sourceTask.Comment, task.Comment) + assert.Equal(t, sourceTask.ErrorIntegration, task.ErrorIntegration) + assert.Equal(t, sourceTask.Schedule, task.Schedule) + assert.Equal(t, sourceTask.TaskRelations, task.TaskRelations) }) - t.Run("drop task: existing", func(t *testing.T) { - request := createTaskBasicRequest(t) - id := request.GetName() - - err := client.Tasks.Create(ctx, request) + t.Run("create or alter: complete", func(t *testing.T) { + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + err := client.Tasks.CreateOrAlter(ctx, sdk.NewCreateOrAlterTaskRequest(id, sql). + WithWarehouse(*sdk.NewCreateTaskWarehouseRequest().WithWarehouse(testClientHelper().Ids.WarehouseId())). + WithSchedule("10 MINUTES"). + WithConfig(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`). + WithAllowOverlappingExecution(true). + WithUserTaskTimeoutMs(10). + WithSessionParameters(sdk.SessionParameters{ + // TODO(SNOW-1348116 - next prs): fill and assert parameters + Autocommit: sdk.Bool(true), + }). + WithSuspendTaskAfterNumFailures(15). + WithComment("some_comment"). + WithTaskAutoRetryAttempts(15). + WithWhen(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`), + ) require.NoError(t, err) + t.Cleanup(testClientHelper().Task.DropFunc(t, id)) - err = client.Tasks.Drop(ctx, sdk.NewDropTaskRequest(id)) + task, err := client.Tasks.ShowByID(ctx, id) require.NoError(t, err) + createdOn := task.CreatedOn - _, err = client.Tasks.ShowByID(ctx, id) - assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) - }) - - t.Run("drop task: non-existing", func(t *testing.T) { - err := client.Tasks.Drop(ctx, sdk.NewDropTaskRequest(NonExistingSchemaObjectIdentifier)) - assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) - }) - - t.Run("alter task: set value and unset value", func(t *testing.T) { - task := createTask(t) - id := task.ID() + assertions.AssertThat(t, objectassert.TaskFromObject(t, task). + HasWarehouse(testClientHelper().Ids.WarehouseId().Name()). + HasSchedule("10 MINUTES"). + HasConfig(`{"output_dir": "/temp/test_directory/", "learning_rate": 0.1}`). + HasAllowOverlappingExecution(true). + HasCondition(`SYSTEM$STREAM_HAS_DATA('MYSTREAM')`). + HasComment("some_comment"). + HasTaskRelations(sdk.TaskRelations{}), + ) - alterRequest := sdk.NewAlterTaskRequest(id).WithSet(sdk.NewTaskSetRequest().WithComment(sdk.String("new comment")).WithUserTaskTimeoutMs(sdk.Int(1000))) - err := client.Tasks.Alter(ctx, alterRequest) + err = client.Tasks.CreateOrAlter(ctx, sdk.NewCreateOrAlterTaskRequest(id, sql)) require.NoError(t, err) alteredTask, err := client.Tasks.ShowByID(ctx, id) require.NoError(t, err) - assert.Equal(t, "new comment", alteredTask.Comment) + assertions.AssertThat(t, objectassert.TaskFromObject(t, alteredTask). + HasWarehouse(""). + HasSchedule(""). + HasConfig(""). + HasAllowOverlappingExecution(false). + HasCondition(""). + HasComment(""). + HasTaskRelations(sdk.TaskRelations{}), + ) - alterRequest = sdk.NewAlterTaskRequest(id).WithUnset(sdk.NewTaskUnsetRequest().WithComment(sdk.Bool(true)).WithUserTaskTimeoutMs(sdk.Bool(true))) - err = client.Tasks.Alter(ctx, alterRequest) - require.NoError(t, err) + require.Equal(t, createdOn, alteredTask.CreatedOn) + }) - alteredTask, err = client.Tasks.ShowByID(ctx, id) + t.Run("drop task: existing", func(t *testing.T) { + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) + + err := client.Tasks.Drop(ctx, sdk.NewDropTaskRequest(task.ID())) require.NoError(t, err) - assert.Equal(t, "", alteredTask.Comment) + _, err = client.Tasks.ShowByID(ctx, task.ID()) + assert.ErrorIs(t, err, sdk.ErrObjectNotFound) + }) + + t.Run("drop task: non-existing", func(t *testing.T) { + err := client.Tasks.Drop(ctx, sdk.NewDropTaskRequest(NonExistingSchemaObjectIdentifier)) + assert.ErrorIs(t, err, sdk.ErrObjectNotExistOrAuthorized) + }) + + t.Run("alter task: set value and unset value", func(t *testing.T) { + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) + + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithSet(*sdk.NewTaskSetRequest(). + // TODO(SNOW-1348116): Cannot set warehouse due to Snowflake error + // WithWarehouse(testClientHelper().Ids.WarehouseId()). + WithErrorNotificationIntegration(errorIntegrationId). + WithSessionParameters(sdk.SessionParameters{ + Autocommit: sdk.Bool(true), + ClientSessionKeepAlive: sdk.Bool(true), + // TODO(SNOW-1348116 - next prs): fill and assert parameters + }). + WithSchedule("10 MINUTE"). + WithConfig(`$${"output_dir": "/temp/test_directory/", "learning_rate": 0.1}$$`). + WithAllowOverlappingExecution(true). + WithUserTaskTimeoutMs(1000). + WithSuspendTaskAfterNumFailures(100). + WithComment("new comment"). + WithTaskAutoRetryAttempts(10). + WithUserTaskMinimumTriggerIntervalInSeconds(15), + )) + require.NoError(t, err) + + // TODO(SNOW-1348116 - next prs): Assert parameters + // assertions.AssertThat(t, objectparametersassert.TaskParameters(t, task.ID()). + // HasUserTaskManagedInitialWarehouseSize() + // ) + + assertions.AssertThat(t, objectassert.Task(t, task.ID()). + // HasWarehouse(testClientHelper().Ids.WarehouseId().Name()). + HasErrorIntegration(sdk.Pointer(errorIntegrationId)). + HasSchedule("10 MINUTE"). + HasConfig(`{"output_dir": "/temp/test_directory/", "learning_rate": 0.1}`). + HasAllowOverlappingExecution(true). + HasComment("new comment"), + ) + + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithUnset(*sdk.NewTaskUnsetRequest(). + WithErrorIntegration(true). + WithSessionParametersUnset(sdk.SessionParametersUnset{ + Autocommit: sdk.Bool(true), + ClientSessionKeepAlive: sdk.Bool(true), + }). + WithWarehouse(true). + WithSchedule(true). + WithConfig(true). + WithAllowOverlappingExecution(true). + WithUserTaskTimeoutMs(true). + WithSuspendTaskAfterNumFailures(true). + WithComment(true). + WithTaskAutoRetryAttempts(true). + WithUserTaskMinimumTriggerIntervalInSeconds(true), + )) + require.NoError(t, err) + + assertions.AssertThat(t, objectassert.Task(t, task.ID()). + HasErrorIntegration(nil). + HasSchedule(""). + HasConfig(""). + HasAllowOverlappingExecution(false). + HasComment(""), + ) + + // TODO(SNOW-1348116 - next prs): Assert parameters + // assertions.AssertThat(t, objectparametersassert.TaskParameters(t, task.ID()). + // HasUserTaskManagedInitialWarehouseSize() + // ) }) t.Run("alter task: set and unset tag", func(t *testing.T) { tag, tagCleanup := testClientHelper().Tag.CreateTag(t) t.Cleanup(tagCleanup) - task := createTask(t) - id := task.ID() + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) tagValue := "abc" - tags := []sdk.TagAssociation{ + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithSetTags([]sdk.TagAssociation{ { Name: tag.ID(), Value: tagValue, }, - } - alterRequestSetTags := sdk.NewAlterTaskRequest(id).WithSetTags(tags) - - err := client.Tasks.Alter(ctx, alterRequestSetTags) + })) require.NoError(t, err) - returnedTagValue, err := client.SystemFunctions.GetTag(ctx, tag.ID(), id, sdk.ObjectTypeTask) + returnedTagValue, err := client.SystemFunctions.GetTag(ctx, tag.ID(), task.ID(), sdk.ObjectTypeTask) require.NoError(t, err) assert.Equal(t, tagValue, returnedTagValue) - unsetTags := []sdk.ObjectIdentifier{ + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithUnsetTags([]sdk.ObjectIdentifier{ tag.ID(), - } - alterRequestUnsetTags := sdk.NewAlterTaskRequest(id).WithUnsetTags(unsetTags) - - err = client.Tasks.Alter(ctx, alterRequestUnsetTags) + })) require.NoError(t, err) - _, err = client.SystemFunctions.GetTag(ctx, tag.ID(), id, sdk.ObjectTypeTask) + _, err = client.SystemFunctions.GetTag(ctx, tag.ID(), task.ID(), sdk.ObjectTypeTask) require.Error(t, err) }) t.Run("alter task: resume and suspend", func(t *testing.T) { - request := createTaskBasicRequest(t). - WithSchedule(sdk.String("10 MINUTE")) - - task := createTaskWithRequest(t, request) - id := task.ID() + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + task, taskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(id, sql).WithSchedule("10 MINUTE")) + t.Cleanup(taskCleanup) assert.Equal(t, sdk.TaskStateSuspended, task.State) - alterRequest := sdk.NewAlterTaskRequest(id).WithResume(sdk.Bool(true)) - err := client.Tasks.Alter(ctx, alterRequest) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(id).WithResume(true)) require.NoError(t, err) alteredTask, err := client.Tasks.ShowByID(ctx, id) @@ -450,8 +597,7 @@ func TestInt_Tasks(t *testing.T) { assert.Equal(t, sdk.TaskStateStarted, alteredTask.State) - alterRequest = sdk.NewAlterTaskRequest(id).WithSuspend(sdk.Bool(true)) - err = client.Tasks.Alter(ctx, alterRequest) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(id).WithSuspend(true)) require.NoError(t, err) alteredTask, err = client.Tasks.ShowByID(ctx, id) @@ -461,102 +607,124 @@ func TestInt_Tasks(t *testing.T) { }) t.Run("alter task: remove after and add after", func(t *testing.T) { - request := createTaskBasicRequest(t). - WithSchedule(sdk.String("10 MINUTE")) + rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() + rootTask, rootTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule("10 MINUTE")) + t.Cleanup(rootTaskCleanup) - otherTask := createTaskWithRequest(t, request) - otherId := otherTask.ID() + task, taskCleanup := testClientHelper().Task.CreateWithAfter(t, rootTask.ID()) + t.Cleanup(taskCleanup) - request = createTaskBasicRequest(t). - WithAfter([]sdk.SchemaObjectIdentifier{otherId}) + assert.Contains(t, task.Predecessors, rootTask.ID()) - task := createTaskWithRequest(t, request) - id := task.ID() + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithRemoveAfter([]sdk.SchemaObjectIdentifier{rootTask.ID()})) + require.NoError(t, err) - assert.Contains(t, task.Predecessors, otherId) + task, err = client.Tasks.ShowByID(ctx, task.ID()) - alterRequest := sdk.NewAlterTaskRequest(id).WithRemoveAfter([]sdk.SchemaObjectIdentifier{otherId}) + require.NoError(t, err) + assert.Empty(t, task.Predecessors) - err := client.Tasks.Alter(ctx, alterRequest) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithAddAfter([]sdk.SchemaObjectIdentifier{rootTask.ID()})) require.NoError(t, err) - task, err = client.Tasks.ShowByID(ctx, id) + task, err = client.Tasks.ShowByID(ctx, task.ID()) require.NoError(t, err) - assert.Empty(t, task.Predecessors) + assert.Contains(t, task.Predecessors, rootTask.ID()) + }) - alterRequest = sdk.NewAlterTaskRequest(id).WithAddAfter([]sdk.SchemaObjectIdentifier{otherId}) + t.Run("alter task: set and unset final task", func(t *testing.T) { + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) - err = client.Tasks.Alter(ctx, alterRequest) + finalTask, finalTaskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(finalTaskCleanup) + + assertions.AssertThat(t, objectassert.TaskFromObject(t, task). + HasTaskRelations(sdk.TaskRelations{ + FinalizerTask: nil, + }), + ) + + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithSetFinalize(finalTask.ID())) require.NoError(t, err) - task, err = client.Tasks.ShowByID(ctx, id) + assertions.AssertThat(t, objectassert.TaskFromObject(t, task). + HasTaskRelations(sdk.TaskRelations{ + FinalizerTask: sdk.Pointer(finalTask.ID()), + }), + ) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithUnsetFinalize(true)) require.NoError(t, err) - assert.Contains(t, task.Predecessors, otherId) + + assertions.AssertThat(t, objectassert.TaskFromObject(t, task). + HasTaskRelations(sdk.TaskRelations{ + FinalizerTask: nil, + }), + ) }) t.Run("alter task: modify when and as", func(t *testing.T) { - task := createTask(t) - id := task.ID() + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) newSql := "SELECT CURRENT_DATE" - alterRequest := sdk.NewAlterTaskRequest(id).WithModifyAs(sdk.String(newSql)) - err := client.Tasks.Alter(ctx, alterRequest) + err := client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithModifyAs(newSql)) require.NoError(t, err) - alteredTask, err := client.Tasks.ShowByID(ctx, id) - require.NoError(t, err) - - assert.Equal(t, newSql, alteredTask.Definition) + assertions.AssertThat(t, objectassert.TaskFromObject(t, task).HasDefinition(newSql)) newWhen := `SYSTEM$STREAM_HAS_DATA('MYSTREAM')` - alterRequest = sdk.NewAlterTaskRequest(id).WithModifyWhen(sdk.String(newWhen)) - err = client.Tasks.Alter(ctx, alterRequest) + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithModifyWhen(newWhen)) require.NoError(t, err) - alteredTask, err = client.Tasks.ShowByID(ctx, id) + assertions.AssertThat(t, objectassert.TaskFromObject(t, task).HasCondition(newWhen)) + + err = client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(task.ID()).WithRemoveWhen(true)) require.NoError(t, err) - assert.Equal(t, newWhen, alteredTask.Condition) + assertions.AssertThat(t, objectassert.TaskFromObject(t, task).HasCondition("")) }) t.Run("show task: default", func(t *testing.T) { - task1 := createTask(t) - task2 := createTask(t) + task1, task1Cleanup := testClientHelper().Task.Create(t) + t.Cleanup(task1Cleanup) + + task2, task2Cleanup := testClientHelper().Task.Create(t) + t.Cleanup(task2Cleanup) - showRequest := sdk.NewShowTaskRequest() - returnedTasks, err := client.Tasks.Show(ctx, showRequest) + returnedTasks, err := client.Tasks.Show(ctx, sdk.NewShowTaskRequest().WithIn(sdk.In{Schema: testClientHelper().Ids.SchemaId()})) require.NoError(t, err) - assert.LessOrEqual(t, 2, len(returnedTasks)) + require.Len(t, returnedTasks, 2) assert.Contains(t, returnedTasks, *task1) assert.Contains(t, returnedTasks, *task2) }) t.Run("show task: terse", func(t *testing.T) { - request := createTaskBasicRequest(t). - WithSchedule(sdk.String("10 MINUTE")) - - task := createTaskWithRequest(t, request) + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + task, taskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(id, sql).WithSchedule("10 MINUTE")) + t.Cleanup(taskCleanup) - showRequest := sdk.NewShowTaskRequest().WithTerse(sdk.Bool(true)) - returnedTasks, err := client.Tasks.Show(ctx, showRequest) + returnedTasks, err := client.Tasks.Show(ctx, sdk.NewShowTaskRequest().WithIn(sdk.In{Schema: testClientHelper().Ids.SchemaId()}).WithTerse(true)) require.NoError(t, err) - assert.LessOrEqual(t, 1, len(returnedTasks)) + require.Len(t, returnedTasks, 1) assertTaskTerse(t, &returnedTasks[0], task.ID(), "10 MINUTE") }) t.Run("show task: with options", func(t *testing.T) { - task1 := createTask(t) - task2 := createTask(t) + task1, task1Cleanup := testClientHelper().Task.Create(t) + t.Cleanup(task1Cleanup) - showRequest := sdk.NewShowTaskRequest(). - WithLike(&sdk.Like{Pattern: &task1.Name}). - WithIn(&sdk.In{Schema: testClientHelper().Ids.SchemaId()}). - WithLimit(&sdk.LimitFrom{Rows: sdk.Int(5)}) - returnedTasks, err := client.Tasks.Show(ctx, showRequest) + task2, task2Cleanup := testClientHelper().Task.Create(t) + t.Cleanup(task2Cleanup) + + returnedTasks, err := client.Tasks.Show(ctx, sdk.NewShowTaskRequest(). + WithLike(sdk.Like{Pattern: &task1.Name}). + WithIn(sdk.In{Schema: testClientHelper().Ids.SchemaId()}). + WithLimit(sdk.LimitFrom{Rows: sdk.Int(5)})) require.NoError(t, err) assert.Equal(t, 1, len(returnedTasks)) @@ -565,32 +733,65 @@ func TestInt_Tasks(t *testing.T) { }) t.Run("describe task: default", func(t *testing.T) { - task := createTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) returnedTask, err := client.Tasks.Describe(ctx, task.ID()) require.NoError(t, err) - assertTask(t, returnedTask, task.ID()) + assertTask(t, returnedTask, task.ID(), testClientHelper().Ids.WarehouseId().Name()) }) t.Run("execute task: default", func(t *testing.T) { - task := createTask(t) + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) + + err := client.Tasks.Execute(ctx, sdk.NewExecuteTaskRequest(task.ID())) + require.NoError(t, err) + }) + + t.Run("execute task: retry last after successful last task", func(t *testing.T) { + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) - executeRequest := sdk.NewExecuteTaskRequest(task.ID()) - err := client.Tasks.Execute(ctx, executeRequest) + _, subTaskCleanup := testClientHelper().Task.CreateWithAfter(t, task.ID()) + t.Cleanup(subTaskCleanup) + + err := client.Tasks.Execute(ctx, sdk.NewExecuteTaskRequest(task.ID())) + require.NoError(t, err) + + err = client.Tasks.Execute(ctx, sdk.NewExecuteTaskRequest(task.ID()).WithRetryLast(true)) + require.ErrorContains(t, err, fmt.Sprintf("Cannot perform retry: no suitable run of graph with root task %s to retry.", task.ID().Name())) + }) + + t.Run("execute task: retry last after failed last task", func(t *testing.T) { + task, taskCleanup := testClientHelper().Task.Create(t) + t.Cleanup(taskCleanup) + + id := testClientHelper().Ids.RandomSchemaObjectIdentifier() + _, subTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(id, "select * from not_existing_table")) + t.Cleanup(subTaskCleanup) + + err := client.Tasks.Execute(ctx, sdk.NewExecuteTaskRequest(task.ID())) require.NoError(t, err) + + require.Eventually(t, func() bool { + err := client.Tasks.Execute(ctx, sdk.NewExecuteTaskRequest(task.ID()).WithRetryLast(true)) + return err != nil + }, time.Second, time.Millisecond*500) }) t.Run("temporarily suspend root tasks", func(t *testing.T) { rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - rootTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule(sdk.String("60 minutes"))) + rootTask, rootTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule("60 MINUTES")) + t.Cleanup(rootTaskCleanup) - id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - task := createTaskWithRequest(t, sdk.NewCreateTaskRequest(id, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTask.ID()})) + task, taskCleanup := testClientHelper().Task.CreateWithAfter(t, rootTask.ID()) + t.Cleanup(taskCleanup) - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(true))) t.Cleanup(func() { - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithSuspend(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithSuspend(true))) }) tasksToResume, err := client.Tasks.SuspendRootTasks(ctx, task.ID(), task.ID()) @@ -608,38 +809,49 @@ func TestInt_Tasks(t *testing.T) { require.Equal(t, sdk.TaskStateStarted, rootTaskStatus.State) }) + // Tested graph + // root1 + // \ + // t1 + // / + // root2 + // Because graph validation occurs only after resuming the root task, we assume that Snowflake will throw + // validation error with given graph configuration. t.Run("resume root tasks within a graph containing more than one root task", func(t *testing.T) { rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - rootTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule(sdk.String("60 minutes"))) + rootTask, rootTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule("60 MINUTES")) + t.Cleanup(rootTaskCleanup) secondRootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - secondRootTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(secondRootTaskId, sql).WithSchedule(sdk.String("60 minutes"))) + secondRootTask, secondRootTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(secondRootTaskId, sql).WithSchedule("60 MINUTES")) + t.Cleanup(secondRootTaskCleanup) - id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - _ = createTaskWithRequest(t, sdk.NewCreateTaskRequest(id, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTask.ID(), secondRootTask.ID()})) + _, cleanupTask := testClientHelper().Task.CreateWithAfter(t, rootTask.ID(), secondRootTask.ID()) + t.Cleanup(cleanupTask) - require.ErrorContains(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(sdk.Bool(true))), "The graph has more than one root task (one without predecessors)") - require.ErrorContains(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(secondRootTask.ID()).WithResume(sdk.Bool(true))), "The graph has more than one root task (one without predecessors)") + require.ErrorContains(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(true)), "The graph has more than one root task (one without predecessors)") + require.ErrorContains(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(secondRootTask.ID()).WithResume(true)), "The graph has more than one root task (one without predecessors)") }) t.Run("suspend root tasks temporarily with three sequentially connected tasks - last in DAG", func(t *testing.T) { rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - rootTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule(sdk.String("60 minutes"))) + rootTask, rootTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule("60 MINUTES")) + t.Cleanup(rootTaskCleanup) - middleTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - middleTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(middleTaskId, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTask.ID()})) + middleTask, middleTaskCleanup := testClientHelper().Task.CreateWithAfter(t, rootTask.ID()) + t.Cleanup(middleTaskCleanup) - id := testClientHelper().Ids.RandomSchemaObjectIdentifier() - task := createTaskWithRequest(t, sdk.NewCreateTaskRequest(id, sql).WithAfter([]sdk.SchemaObjectIdentifier{middleTask.ID()})) + task, taskCleanup := testClientHelper().Task.CreateWithAfter(t, middleTask.ID()) + t.Cleanup(taskCleanup) - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(middleTask.ID()).WithResume(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(middleTask.ID()).WithResume(true))) t.Cleanup(func() { - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(middleTask.ID()).WithSuspend(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(middleTask.ID()).WithSuspend(true))) }) - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(true))) t.Cleanup(func() { - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithSuspend(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithSuspend(true))) }) tasksToResume, err := client.Tasks.SuspendRootTasks(ctx, task.ID(), task.ID()) @@ -668,22 +880,23 @@ func TestInt_Tasks(t *testing.T) { t.Run("suspend root tasks temporarily with three sequentially connected tasks - middle in DAG", func(t *testing.T) { rootTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - rootTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule(sdk.String("60 minutes"))) + rootTask, rootTaskCleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(rootTaskId, sql).WithSchedule("60 MINUTES")) + t.Cleanup(rootTaskCleanup) - middleTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - middleTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(middleTaskId, sql).WithAfter([]sdk.SchemaObjectIdentifier{rootTask.ID()})) + middleTask, middleTaskCleanup := testClientHelper().Task.CreateWithAfter(t, rootTask.ID()) + t.Cleanup(middleTaskCleanup) - childTaskId := testClientHelper().Ids.RandomSchemaObjectIdentifier() - childTask := createTaskWithRequest(t, sdk.NewCreateTaskRequest(childTaskId, sql).WithAfter([]sdk.SchemaObjectIdentifier{middleTask.ID()})) + childTask, childTaskCleanup := testClientHelper().Task.CreateWithAfter(t, middleTask.ID()) + t.Cleanup(childTaskCleanup) - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(childTask.ID()).WithResume(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(childTask.ID()).WithResume(true))) t.Cleanup(func() { - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(childTask.ID()).WithSuspend(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(childTask.ID()).WithSuspend(true))) }) - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithResume(true))) t.Cleanup(func() { - require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithSuspend(sdk.Bool(true)))) + require.NoError(t, client.Tasks.Alter(ctx, sdk.NewAlterTaskRequest(rootTask.ID()).WithSuspend(true))) }) tasksToResume, err := client.Tasks.SuspendRootTasks(ctx, middleTask.ID(), middleTask.ID()) @@ -717,24 +930,6 @@ func TestInt_TasksShowByID(t *testing.T) { client := testClient(t) ctx := testContext(t) - cleanupTaskHandle := func(id sdk.SchemaObjectIdentifier) func() { - return func() { - err := client.Tasks.Drop(ctx, sdk.NewDropTaskRequest(id)) - if errors.Is(err, sdk.ErrObjectNotExistOrAuthorized) { - return - } - require.NoError(t, err) - } - } - - createTaskHandle := func(t *testing.T, id sdk.SchemaObjectIdentifier) { - t.Helper() - - err := client.Tasks.Create(ctx, sdk.NewCreateTaskRequest(id, "SELECT CURRENT_TIMESTAMP")) - require.NoError(t, err) - t.Cleanup(cleanupTaskHandle(id)) - } - t.Run("show by id - same name in different schemas", func(t *testing.T) { schema, schemaCleanup := testClientHelper().Schema.CreateSchema(t) t.Cleanup(schemaCleanup) @@ -742,8 +937,10 @@ func TestInt_TasksShowByID(t *testing.T) { id1 := testClientHelper().Ids.RandomSchemaObjectIdentifier() id2 := testClientHelper().Ids.NewSchemaObjectIdentifierInSchema(id1.Name(), schema.ID()) - createTaskHandle(t, id1) - createTaskHandle(t, id2) + _, t1Cleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(id1, "SELECT CURRENT_TIMESTAMP")) + _, t2Cleanup := testClientHelper().Task.CreateWithRequest(t, sdk.NewCreateTaskRequest(id2, "SELECT CURRENT_TIMESTAMP")) + t.Cleanup(t1Cleanup) + t.Cleanup(t2Cleanup) e1, err := client.Tasks.ShowByID(ctx, id1) require.NoError(t, err)