I know that using custom types is a common question, but bear with me...
I would like to define a custom type 'ConnectionInfo' (see below):
type DataSource struct {
gorm.Model
Name string
Type DataSourceType `sql:"type:ENUM('POSTGRES')" gorm:"column:data_source_type"`
ConnectionInfo ConnectionInfo `gorm:"embedded"`
}
I would like to restrict ConnectionInfo to be one of a limited number of types, i.e.:
type ConnectionInfo interface {
PostgresConnectionInfo | MySQLConnectionInfo
}
How can I do this?
My progress thus far:
I defined a ConnectionInfo interface (I now know this is invalid in GORM, but how do I get around it?)
type ConnectionInfo interface {
IsConnectionInfoType() bool
}
I've then implemented this interface with two types (and implemented the scanner and valuer interfaces) like so:
type PostgresConnectionInfo struct {
Host string
Port int
Username string
Password string
DBName string
}
func (PostgresConnectionInfo) IsConnectionInfoType() bool {
return true
}
func (p *PostgresConnectionInfo) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return fmt.Errorf("failed to unmarshal the following to a PostgresConnectionInfo value: %v", value)
}
result := PostgresConnectionInfo{}
if err := json.Unmarshal(bytes, &result); err != nil {
return err
}
*p = result
return nil
}
func (p PostgresConnectionInfo) Value() (driver.Value, error) {
return json.Marshal(p)
}
But of course I get the following error:
unsupported data type: /models.ConnectionInfo