postgres 的 GORM 枚举类型

问题描述 投票:0回答:1

我使用 GORM 来处理 PostgreSQL。 例如,我有一个具有自定义枚举类型的结构:

type MonitoringDatabase struct {
    Name              string       `gorm:"primaryKey"`
    DBType            DbType       `gorm:"type:db_type"`
}

我在我需要的方案中使用 Exec 创建 Enum:

type DbType string

const (
    PostgreSQL DbType = "PostgreSQL"
    Oracle     DbType = "Oracle"
    Ignite     DbType = "Ignite"
)

_, errDbEnum := sqlDB.Exec(fmt.Sprintf("CREATE TYPE %s.db_type AS ENUM ('%s','%s','%s')", PgSchema, PostgreSQL, Oracle, Ignite))

但是在迁移表时,我收到错误(类型“db_type”不存在(SQLSTATE 42704)),因为 GORM 正在公共模式中查找枚举。 我尝试设置 search_path 并配置 NamingStrategy,但没有帮助。模式名称是一个动态参数,不能将其硬编码在标签中

有什么办法可以解决这个问题吗?

postgresql go enums go-gorm
1个回答
0
投票

您的方法不是使用 ORM 的正确方法。

我们定义类型,然后让 ORM 处理 DDL 命令。不直接调用exec来运行DDL命令。

这个是一个很好的示例(注意为枚举类型实现的ScanValue方法):

package main

import (
    "database/sql/driver"
    "fmt"
)

type DbType string

const (
    PostgreSQL DbType = "PostgreSQL"
    Oracle     DbType = "Oracle"
    Ignite     DbType = "Ignite"
)

type MonitoringDatabase struct {
    Name              string       `gorm:"primaryKey"`
    DBType            DbType       `gorm:"type:db_type;default:'PostgreSQL'"`
}

func (st *DbType) Scan(value interface{}) error {
    b, ok := value.([]byte)
    if !ok {
        *st = DbType(b)
    }
    return nil
}

func (st DbType) Value() (driver.Value, error) {
    return string(st), nil
}
© www.soinside.com 2019 - 2024. All rights reserved.