Skip to content

Commit

Permalink
Merge pull request #418 from Neuman968/issue408Fix
Browse files Browse the repository at this point in the history
Fix generating schema fails due to column name conflicts
  • Loading branch information
go-jet authored Oct 28, 2024
2 parents e715b13 + 9f8732c commit 02f19ff
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
12 changes: 11 additions & 1 deletion generator/template/sql_builder_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/go-jet/jet/v2/generator/metadata"
"github.com/go-jet/jet/v2/internal/utils/dbidentifier"
"path"
"slices"
"strings"
"unicode"
)
Expand Down Expand Up @@ -134,10 +135,19 @@ type TableSQLBuilderColumn struct {
Type string
}

var reservedKeywords = []string{"TableName", "Table", "SchemaName", "Alias", "AllColumns", "MutableColumns"}

func renameIfReserved(name string) string {
if slices.Contains(reservedKeywords, name) {
return name + "_"
}
return name
}

// DefaultTableSQLBuilderColumn returns default implementation of TableSQLBuilderColumn
func DefaultTableSQLBuilderColumn(columnMetaData metadata.Column) TableSQLBuilderColumn {
return TableSQLBuilderColumn{
Name: dbidentifier.ToGoIdentifier(columnMetaData.Name),
Name: renameIfReserved(dbidentifier.ToGoIdentifier(columnMetaData.Name)),
Type: getSqlBuilderColumnType(columnMetaData),
}
}
Expand Down
25 changes: 25 additions & 0 deletions generator/template/sql_builder_template_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package template

import (
"github.com/go-jet/jet/v2/generator/metadata"
"github.com/stretchr/testify/require"
"testing"
)
Expand All @@ -9,3 +10,27 @@ func TestToGoEnumValueIdentifier(t *testing.T) {
require.Equal(t, defaultEnumValueName("enum_name", "enum_value"), "EnumValue")
require.Equal(t, defaultEnumValueName("NumEnum", "100"), "NumEnum100")
}

func TestColumnRenameReserved(t *testing.T) {
tests := []struct {
col string
want string
}{
{col: "TableName", want: "TableName_"},
{col: "Table", want: "Table_"},
{col: "SchemaName", want: "SchemaName_"},
{col: "Alias", want: "Alias_"},
{col: "AllColumns", want: "AllColumns_"},
{col: "MutableColumns", want: "MutableColumns_"},
{col: "OtherColumn", want: "OtherColumn"},
}

for _, tt := range tests {
t.Run(tt.col, func(t *testing.T) {
builder := DefaultTableSQLBuilderColumn(metadata.Column{
Name: tt.col,
})
require.Equal(t, builder.Name, tt.want)
})
}
}

0 comments on commit 02f19ff

Please sign in to comment.