Cross-posted from “What would be the best way to store the country of a user in SQL?” by @lena@gregtech.eu in !learn_programming@programming.dev


I use Gorm. This is the current code:

package main

import (
	"fmt"
	"log"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Env struct {
	DB     *gorm.DB
	Logger *log.Logger
}

type User struct {
	ID           uint
	Username     string
	Name         string
	Email        string
	PasswordHash string
	Country      string //should probably be a foreign key of another table
}

func initDB() {
	env := &Env{}
	db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
	if err != nil {
		fmt.Printf("Error opening database: %v", err)
		return
	}
	env.DB = db
	env.DB.AutoMigrate(&User{})

}

func main() {
	initDB()
}

As you can see in the comment in the code, I assume the best way would be to have a table of countries and then assign each user to one via a foreign key. However, it seems a bit cumbersome to manually create a list of all countries. Is there a better way to do this?

  • locuester@lemmy.zip
    link
    fedilink
    English
    arrow-up
    1
    ·
    edit-2
    13 hours ago

    Heya, long time dev here.

    If you’re not expecting millions of rows, you could just use the country code directly in the user table and not use a foreign key/table at all. Just an idea.

    However, if you want the country table, i would find this list in a csv format (or copy paste into goog sheets or such and massage it) and then use a tool or write a quick script to ingest it into the db. If you’re doing that you should design the country table to have id, code, name. It can be used for populating dropdowns or autocomplete or such too.

    Over-engineering is a thing; keep it simple. If you’re doing this mainly as an exercise to learn, over-engineering can be ok - just understand that it doesn’t HAVE to be done any particular way, and there is no “right” way. Design is subjective and varies based on the needs of your software.