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?
Which country list will you use? Some countries are not recognized universally. Some countries have different names depending on where you are (Macedonia is known as Former Yugoslavic Republic of Macedonia in Greece and several other countries, mainly because Greece was being bitchy).
The point is, there isn’t one best practice because a country list is inherently political. And politics are always messy.
But yeah, a FK to a countries table is reasonable. Good luck.
Since 2018 they’re actually now The Republic of North Macedonia as per the Prespa Agreement between North Macedonia and the Hellenic Republic.
Which really goes to illustrate your point about politics and show you can’t rely on names to be permanent keys for joining anything.
Give this a read while you’re at it.
Beautiful.
- You get a reliable list of official country codes like this one: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes
- You don’t manually import it, you write some kind of script to do that for you