I've been trying to setup a project with Go Fiber and use GORM in it. My app is successfully connected to the postgres database but when trying go get data from database i'm getting error
"error": "ERROR: relation \"users\" does not exist (SQLSTATE 42P01)"
I'm using the following packages:
my application is setup as follows
Makefile
include .env
MIGRATIONS_FOLDER = ./database/migrations
DB_DSN="postgres://${DB_USERNAME}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME}?sslmode=${DB_SSL_MODE}"
migrate.create:
@if [ "$(name)" = "" ]; then \
echo "Error: Please provide a migration name using 'name=your_migration_name'"; \
exit 1; \
fi
migrate create -ext sql -dir $(MIGRATIONS_FOLDER) $(name)
migrate.up:
migrate -path $(MIGRATIONS_FOLDER) -database "$(DATABASE_URL)" up
database.go
package config
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"log"
)
type Dbinstance struct {
Db *gorm.DB
}
var DB Dbinstance
// connectDb
func ConnectDb() {
env := NewEnv()
dsn := env.DBUrl
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: gormLogger.Default.LogMode(gormLogger.Info),
})
if err != nil {
log.Fatal("Failed to connect to database. \n", err)
}
log.Println("connected")
db.Logger = gormLogger.Default.LogMode(gormLogger.Info)
DB = Dbinstance{
Db: db,
}
}
bootstrap.go
func NewApplication() *fiber.App {
app := fiber.New(fiber.Config{
Prefork: true,
CaseSensitive: true,
StrictRouting: true,
ServerHeader: "Fiber",
AppName: "Test App v1.0.1",
})
config.ConnectDb()
router.Setup(app)
return app
}
user.model.go
package model
import "github.com/bantawao4/gofiber-boilerplate/app/dao"
type UserModel struct {
dao.User
}
user.gen.go
package dao
import (
"time"
"gorm.io/gorm"
)
const TableNameUser = "users"
// User mapped from table <users>
type User struct {
ID string `gorm:"column:id;type:uuid;primaryKey;default:gen_random_uuid()" json:"id"`
FullName string `gorm:"column:full_name;type:character varying(45);not null" json:"full_name"`
Phone string `gorm:"column:phone;type:character varying(15);not null" json:"phone"`
Gender string `gorm:"column:gender;type:character varying(15);not null" json:"gender"`
Email string `gorm:"column:email;type:character varying(100);not null" json:"email"`
Password string `gorm:"column:password;type:character varying(100);not null" json:"password"`
CreatedAt time.Time `gorm:"column:created_at;type:timestamp without time zone;not null" json:"created_at"`
UpdatedAt *time.Time `gorm:"column:updated_at;type:timestamp without time zone" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:timestamp without time zone" json:"deleted_at"`
}
// TableName User's table name
func (*User) TableName() string {
return TableNameUser
}
user.repository.go
package repository
import (
"github.com/bantawao4/gofiber-boilerplate/app/model"
"github.com/bantawao4/gofiber-boilerplate/config"
"gorm.io/gorm"
)
type UserRepository interface {
GetUsers() ([]model.UserModel, error)
CreateUser(user *model.UserModel) (*model.UserModel, error)
}
type userRepository struct {
db *gorm.DB
}
func NewUserRepository() UserRepository {
return &userRepository{
db: config.DB.Db,
}
}
func (r *userRepository) GetUsers() ([]model.UserModel, error) {
var users []model.UserModel
err := r.db.Find(&users).Error
return users, err
}
func (r *userRepository) CreateUser(user *model.UserModel) (*model.UserModel, error) {
err := r.db.Create(&user).Error
if err != nil {
return nil, err
}
return user, nil
}
I'm creating migration files and running migration to create tables in database with success. But when hit /api/users
route i'm getting the above mentioned error.
Is my setup messed up to cause the error ?
More details on files and folder structure can be found on:
I found that your .env file contains DATABASE_URL which will be used for makefile to do migration up (https://github.com/bantawa04/go-fiber-boilerplate/blob/016a2b45c06882aea0d1efb8123e0cecdac427e2/.env#L11) i believe that your migration up is failed because your database host is database in .env file which is not pointing to anywhere. to make your code works your need to update DATABASE_URL from
postgresql://${DB_USERNAME}:${DB_PASSWORD}@database:5432/${DB_NAME}?sslmode=${DB_SSL_MODE}
to
postgresql://${DB_USERNAME}:${DB_PASSWORD}@{DB_HOST}:5432/${DB_NAME}?sslmode=${DB_SSL_MODE}
DB_HOST can be anything like localhost, ip address or your database's host in other server.