Skip to content

Add ColumnTypeMap which allows bespoke customisation of column types. #1336

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

RParkerHp
Copy link

@RParkerHp RParkerHp commented Jun 16, 2025

  • [Y] Do only one thing
  • [Y] Non breaking API changes
  • [Y] Tested

What did this pull request do?

  • Adds WithColumnTypeMap which mirrors functionality of WithDataTypeMap but for columns.

User Case Description

  • For varchar, nvarchar, etc, I need to get the length of the field (e.g. nvarchar(25).

    This is implemented in the following way:

var customColumnMap = map[string]func(columnType gorm.ColumnType) (dataType string){
   "varchar":  getColumnTypeAndSize,
}

cfg.WithColumnTypeMap(customColumnMap)

func getColumnTypeAndSize(columnType gorm.ColumnType) (dataType string) {
	typ, ok := columnType.ColumnType()
	if ok {
		len, ok := columnType.Length()
		if ok && len > 0 {
			typ = fmt.Sprintf("%v(%v)", typ, len)
		} else if len == -1 && strings.Contains(typ, "char") {
			typ += "(max)"
		}

		return typ
	}

	panic(fmt.Errorf("unable to process column '%v'", columnType.Name()))
}

@dushaoshuai
Copy link

Adds helper.SetDataType in order to override and add data type values.

The value used for bit in the dataType map does not match my requirement that it contains the value bool (rather than []uint8), hence the creation of SetDataType function, which allows this value to be modified. This also allows a new mapping to be created: 'uniqueidentifier' to 'uuid.UUID'.

Is it WithDataTypeMap, or am I missing something?

@RParkerHp
Copy link
Author

Adds helper.SetDataType in order to override and add data type values.
The value used for bit in the dataType map does not match my requirement that it contains the value bool (rather than []uint8), hence the creation of SetDataType function, which allows this value to be modified. This also allows a new mapping to be created: 'uniqueidentifier' to 'uuid.UUID'.

Is it WithDataTypeMap, or am I missing something?

You are absolutely right. Sorry about that. I have reverted the GetDataType and SetDataType changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants