pyprism
pyprism

Reputation: 3008

gorm failed to create tables without any errors

I am using postgres and gorm. Here are my models:

package models

import "github.com/jinzhu/gorm"

type User struct {
    gorm.Model
    Username  string `gorm:"unique_index;not null"`
    Hash      string `gorm:"not null"`
    IsAdmin   bool   `gorm:"not null"`
    IsUser    bool   `gorm:"not null"`
    IsActive  bool   `gorm:"not null"`
    RegEmail  bool   `gorm:"not null"`
    RegFb     bool   `gorm:"not null"`
    RegGoogle bool   `gorm:"not null"`
}

type NewsPaper struct {
    gorm.Model
    Name     string `gorm:"not null"`
    NamBN    string `gorm:"not null"`
    LogoUrl  string `gorm:"not null"`
    Slug     string `gorm:"unique_index;not null"`
    IsActive bool   `gorm:"not null"`
    IsWeb    bool   `gorm:"not null"`
    IsMobile bool   `gorm:"not null"`
}

and db functions:

package bootstrap

import (
    "fmt"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
    "github.com/u/projName/models"
)

var db *gorm.DB

// initialize database
func Init() {
    var adapter string
    adapter = App.DBConfig.String("adapter")
    switch adapter {
    case "postgres":
        postgresConn()
        break
    default:
        panic("Undefined connection on config.local.yaml")
    }
}

func postgresConn() {
    var (
        connectionString string
        err              error
    )
    connectionString = fmt.Sprintf("connection info")
    if db, err = gorm.Open("postgres", connectionString); err != nil {
        panic(err)
    }
    if err = db.DB().Ping(); err != nil {
        panic(err)
    }

    db.LogMode(true)
}

//Gorm: return GORM's postgres database connection instance.
func DBManager() *gorm.DB {
    var adapter string
    adapter = App.DBConfig.String("adapter")
    switch adapter {
    case "postgres":
        postgresConn()
        break
    default:
        panic("Undefined connection on config.yaml")
    }
    err := db.AutoMigrate(&models.NewsPaper{}, &models.User{}).Error
    if err != nil {
        panic(err)
    }
    return db
}

When I run the main function it doesn't throws any errors. I checked database there was no table.

Upvotes: 1

Views: 2041

Answers (1)

ahmetlutfu
ahmetlutfu

Reputation: 325

You must call gorm migrate function with your models.

db.AutoMigrate(&User{},&NewsPaper{})

it will create table for your models.

Upvotes: 2

Related Questions