diff --git a/generator/template/sql_builder_template.go b/generator/template/sql_builder_template.go index fe7fba59..16f88b84 100644 --- a/generator/template/sql_builder_template.go +++ b/generator/template/sql_builder_template.go @@ -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" ) @@ -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), } } diff --git a/generator/template/sql_builder_template_test.go b/generator/template/sql_builder_template_test.go index b3719d7a..25834fc2 100644 --- a/generator/template/sql_builder_template_test.go +++ b/generator/template/sql_builder_template_test.go @@ -1,6 +1,7 @@ package template import ( + "github.com/go-jet/jet/v2/generator/metadata" "github.com/stretchr/testify/require" "testing" ) @@ -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) + }) + } +}