From eebb094531656fd874b86381f0477408571888f4 Mon Sep 17 00:00:00 2001 From: Paulius Venclovas Date: Fri, 6 Sep 2024 15:56:20 +0300 Subject: [PATCH] issue-3865 add formating for new lines and tabs --- catalog/resource_sql_table.go | 15 +++++++++++++++ catalog/resource_sql_table_test.go | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/catalog/resource_sql_table.go b/catalog/resource_sql_table.go index 922d2d0cd2..27fd055b6d 100644 --- a/catalog/resource_sql_table.go +++ b/catalog/resource_sql_table.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "reflect" + "regexp" "slices" "strings" "time" @@ -369,6 +370,7 @@ func (ti *SqlTableInfo) diff(oldti *SqlTableInfo) ([]string, error) { if ti.TableType == "VIEW" { // View only attributes + formatViewDefinition(ti) if ti.ViewDefinition != oldti.ViewDefinition { statements = append(statements, fmt.Sprintf("ALTER VIEW %s AS %s", ti.SQLFullName(), ti.ViewDefinition)) } @@ -408,6 +410,19 @@ func (ti *SqlTableInfo) diff(oldti *SqlTableInfo) ([]string, error) { return statements, nil } +// formatViewDefinition removes empty lines and changes tabs to 4 spaces +// in order to compare view definitions correctly +func formatViewDefinition(ti *SqlTableInfo) { + + // remove empty lines + // 1\n\n\n2 => 1\n2 + ti.ViewDefinition = regexp.MustCompile(`[\r\n]+`).ReplaceAllString(ti.ViewDefinition, "\n") + + // change tab to 4 spaces + // 1\t2 => 1 2 + ti.ViewDefinition = strings.ReplaceAll(ti.ViewDefinition, "\t", " ") +} + func (ti *SqlTableInfo) updateTable(oldti *SqlTableInfo) error { statements, err := ti.diff(oldti) if err != nil { diff --git a/catalog/resource_sql_table_test.go b/catalog/resource_sql_table_test.go index 795a1d3f31..ddd4541e3a 100644 --- a/catalog/resource_sql_table_test.go +++ b/catalog/resource_sql_table_test.go @@ -1710,3 +1710,17 @@ func TestSqlTablesAPI_getTable_OptionsAndParametersProcessedCorrectly(t *testing }) } } + +func TestFormatViewDefinition(t *testing.T) { + ti := &SqlTableInfo{ + ViewDefinition: "SELECT\n\n\n\t*\nFROM\n\tmy_table\nWHERE\n\tcolumn = 'value'", + } + + expected := "SELECT\n *\nFROM\n my_table\nWHERE\n column = 'value'" + + formatViewDefinition(ti) + + if ti.ViewDefinition != expected { + t.Errorf("Expected view definition: %s, but got: %s", expected, ti.ViewDefinition) + } +}