如何使用gorm设置特定的数据库架构?

时间:2019-01-15 17:15:17

标签: database go database-connection go-gorm

我正在开发CRUD应用程序。我正在从api中读取JSON,我想在特定模式下使用“ database / sql”和GORM在数据库中编写此JSON 结构:

type Veiculo struct {
gorm.Model
Codigo                int       `json:"vei_codigo"`
Placa                 string    `json:"vei_placa"`
Nome                  string    `json:"vei_nome"`
}

端点函数:

func CreateVeiculo(c *gin.Context) {

var veiculo model.Veiculo
//id := c.Params.ByName("id")

c.BindJSON(&veiculo)
c.JSON(200, veiculo)

psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+" password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
dbVeiculosGorm, err := gorm.Open("postgres", psqlInfo)
if err != nil {
    panic(err)
}
defer dbVeiculosGorm.Close()

dbVeiculosGorm.AutoMigrate(&model.Veiculo{})

//t := time.Now()
//ts := t.Format("2006-01-02 15:04:05")

dbVeiculosGorm.Create(&model.Veiculo{Placa: veiculo.Placa, Nome: veiculo.Nome}

,但是数据库无法访问。有多个架构。我必须设置特定的架构吗?我在做什么错了?

10 个答案:

答案 0 :(得分:1)

除了 Alan.WCR 以大写表格名称,

gorm.DefaultTableNameHandler = func(db *gorm.DB, table string) string {
    var tableName string
    names := strings.Split(table, "_")
    for _, name := range names {
        tableName = tableName + strings.Title(name)
    }
    return "Users." + tableName
}

答案 1 :(得分:0)

这是一个基本示例,说明您需要通过 gorm 将一些简单数据
插入 PostgreSQL 数据库中。

  

main.go

package main

import (
    "log"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres" // Don't forget the dialect
)

// Simple Example model
type FuelType struct {
    gorm.Model // Gorm default columns (id, created_at, updated_at, deleted_at)
    Name string
}

func main() {
    // Database initialization
    db, err := gorm.Open(
        "postgres",
        "host=localhost port=5432 user=postgres dbname=foo password=bar sslmode=disable",
    )
    if err != nil {
        log.Fatalln("Can't connect to the db: ", err)
    }
    defer func() {
        if err := db.Close(); err != nil {
            log.Fatalln("Can't close the db connection: ", err)
        }
    }()

    // Migration
    db.AutoMigrate(&FuelType{})

    // Insertion
    fuelType := FuelType{Name: "100 GFuel"}
    db.Create(&fuelType)
}

答案 2 :(得分:0)

自动迁移之前

gorm.DefaultTableNameHandler = func(dbVeiculosGorm *gorm.DB, defaultTableName string) string {
    return "your schema name." + defaultTableName
}

dbVeiculosGorm.AutoMigrate(&model.Veiculo{})

答案 3 :(得分:0)

我在数据库中使用此配置,并使用带有postgresql的单数名称。

gorm.DefaultTableNameHandler = func(db *gorm.DB, table string) string {
    fmt.Printf(table)
    return "schema_name." + table[:len(table)-1]
}

答案 4 :(得分:0)

我尚无评论的声誉,或者我将对Yurifull的帖子发表评论。值得一提的是,单数化比切掉最后一个字符要复杂得多。幸运的是,jinzhu将单数化逻辑拆分到了自己的程序包中,因此我们可以更新Yurifull的代码,如下所示:

import (
    "github.com/jinzhu/inflection"
)

...

gorm.DefaultTableNameHandler = func(db *gorm.DB, table string) string {
    fmt.Printf(table)
    return "schema_name." + inflection.Singular(table)
}

答案 5 :(得分:0)

要在 create 语句中指定特定架构,请像这样修改代码:

dbVeiculosGorm.Table("schema.tablename").Create(&model.Veiculo{Placa: veiculo.Placa, Nome: veiculo.Nome}

要为您的迁移操作指定架构,请添加以下方法:

type Veiculo struct {
    gorm.Model
    Codigo int    `json:"vei_codigo"`
    Placa  string `json:"vei_placa"`
    Nome   string `json:"vei_nome"`
}

func (u *Veiculo) TableName() string {
    // custom table name, this is default
    return "schema.veiculo"
}

答案 6 :(得分:0)

如果您使用的是最新版本的 gorm,这将不起作用:

gorm.DefaultTableNameHandler = func(dbVeiculosGorm *gorm.DB, defaultTableName string) string {
    return "your schema name." + defaultTableName
}

dbVeiculosGorm.AutoMigrate(&model.Veiculo{})

而是在 gorm 配置中定义您的命名约定。示例:

    dsn := "host=localhost user=myuser dbname=golang_tutorial port=5432"
    db,err := gorm.Open(postgres.Open(dsn), &gorm.Config{
            NamingStrategy: schema.NamingStrategy{
                TablePrefix: "golang_crud.", // schema name  
                SingularTable: true,
            },
    })

答案 7 :(得分:0)

@hbswift 的回答也对我有用,但我之前尝试过一些受最新 gorm Close 想法启发而有所不同的方法。

func ConnectDB() (db *gorm.DB, err error) {
    db, err = gorm.Open(postgres.New(postgres.Config{
        DSN:                  `user=postgres password=a12345 dbname=YOUR-DB-NAME port=5432 sslmode=disable`,
        PreferSimpleProtocol: true, // disables implicit prepared statement usage. By default pgx automatically uses the extended protocol
    }), &gorm.Config{})
    return
}


func main() {
    var sqlDB *sql.DB
    var db *gorm.DB
    {
        var err error
        db, err = ConnectDB()
        if err != nil {
            os.Exit(-1)
        }
        sqlDB, _ = db.DB()
        sqlDB.Exec(`set search_path='Schema-Name'`)
    }
    defer sqlDB.Close()

}

答案 8 :(得分:0)

使用 GORM 2.0 这会起作用。

func ConnectDB() (db *gorm.DB, err error) {
    db, err = gorm.Open(postgres.New(postgres.Config{
        DSN:                  `user=test password=test dbname=DB-NAME port=5432 sslmode=disable`,
        PreferSimpleProtocol: true,
    }), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            TablePrefix:   "YOUR_SCHEMA_NAME.", // schema name
            SingularTable: false,
        }})
    return
}

答案 9 :(得分:-1)

这是我的设置(版本 go1.16.5 darwin/amd64):

参考:https://github.com/go-gorm/postgres

// Setup initializes the database instance
func Setup() {

   var err error
   Db, err = gorm.Open(postgres.New(postgres.Config{
      DSN: fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=UTC",
        "localhost",
        "DB Username",
        "DB Password",
        "DbName"
        5432),
       PreferSimpleProtocol: true, 
   }), &gorm.Config{
       NamingStrategy: schema.NamingStrategy{
        TablePrefix:   "DB Schema Name" + ".", // schema name
        SingularTable: true,
       },
   })

   if err != nil {
       log.WithError(err).Fatalf("Db Error: %s", err)
   }

}