jet icon indicating copy to clipboard operation
jet copied to clipboard

Support columns named `table_name`

Open lawrencejones opened this issue 3 years ago • 1 comments

Is your feature request related to a problem? Please describe.

I want to use go-jet to build Postgres internal schemas, like information_schema. Sadly all these tables have columns called table_name, which means the generated code squats on the TableName struct field.

It used to be that this was fine, but upgrading to 2.7 means we now rely on TableName to be a function, which causes compilation errors like so:

internal/dbschema/information_schema/view/constraint_table_usage.go:39:65: cannot call non-function a.constraintTableUsageTable.TableName (type jet.ColumnString)
internal/dbschema/information_schema/view/constraint_table_usage.go:44:61: cannot call non-function a.constraintTableUsageTable.TableName (type jet.ColumnString)

Describe the solution you'd like

We should alias the output column struct field name, or more securely namespace the TableName() function so it is less likely to clash with database column names.

lawrencejones avatar Jan 30 '22 15:01 lawrencejones

Hi @lawrencejones. It is possible to change field name with generator customization. Similar test: https://github.com/go-jet/jet/blob/f2e4b8551c48b97d0cd2d3deff47dc1b2aa2f04e/tests/postgres/generator_template_test.go#L359

In your case to change SQL builder view field, generator should be something like:

err := postgres.Generate(
	tempTestDir,
	dbConnection,
	template.Default(postgres2.Dialect).
		UseSchema(func(schemaMetaData metadata.Schema) template.Schema {
			return template.DefaultSchema(schemaMetaData).
				UseSQLBuilder(template.DefaultSQLBuilder().
					UseView(func(table metadata.Table) template.TableSQLBuilder {
						return template.DefaultTableSQLBuilder(table).
							UseColumn(func(column metadata.Column) template.TableSQLBuilderColumn {
								defaultColumn := template.DefaultTableSQLBuilderColumn(column)

								if defaultColumn.Name == "TableName" {
									defaultColumn.Name = "TableName_"  //or some other name
								}

								return defaultColumn
							})
					}),
				)
		}),
)

go-jet avatar Jan 31 '22 10:01 go-jet