GORM Model created but not showing data on db.Find()

So I have a global instance of the DB throughout my project. Here’s how I set that up.

type API struct {
    db *gorm.DB
}

I created a package-wide variable called “api” to access within the project.

var api = API{
    db: NewDB()
}

My NewDB function looks like this:

func NewDB() *gorm.DB {
    db, err := gorm.Open("sqlite3", "test.db")

    if err != nil {
        panic(err)
    }

    return db
}

Here’s my Users model. Note that I did not extend gorm.Model in this case.

type User struct {
	ID        uuid.UUID `json:"id" gorm:"primary_key"`
	Email     string    `json:"email" gorm:"not null;unique"`
	Password  string    `json:"password"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	DeletedAt time.Time `json:"deleted_at"`
}

I have included a BeforeEach function atop the User model to fulfill a UUID because I prefer it over autoincrement. The ID works great, when I go inside the sqlite file and run a select * from users query I get returned the id, the email, password, etc.

The issue I’m having is running this code:

func UsersIndex(w http.ResponseWriter, r *http.Request) {
	var users Users

	api.db.Find(&users)

	data, _ := json.Marshal(&users)

	fmt.Fprint(w, string(data))
}

It’s not the error marshalling the JSON, I’ve tried including that, and still nothing. My issue is that no matter what the raw query from SQLite says, I always get a blank list of Users. What’s weird is that it was working when my User model extended gorm.Model, however after I changed it that’s when it stopped working.

Thanks!

What errors do Find and Marshal create? (Find does not return an error but it sets the Error field of the DB struct. Marshal does return an error as the second return value. It is always a good idea to check errors.)

And how did you change the User model? How did it look like when it was still working?

What I noticed is that the DeletedAt field appears to be a pointer to time.Time in the GORM docs. (For whatever reason.) Maybe that’s the problem here.

2 Likes

Wow, thanks a lot. I was missing the fact that DeletedAt is indeed a pointer to time.Time. I changed that and now it works. Thanks for your help!

2 Likes