Cross-posted from “What would be the best way to store the country of a user in SQL?” by @[email protected] in [email protected]
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?
It will depend upon other things you might want to do with it in the future.
If you want the record to stay “correct” in the future, you might want to have a separate entry for nationality information, which will be a 1-to-1 mapping with the other table you make for it. Why? …
This should help determine what kind of change may occur in case of changes in the political landscape in the future, without you requiring to re-ask the form-filler.
Inspired by https://flightaware.engineering/falsehoods-programmers-believe-about-aviation/
And I am going to consider this stuff every time I make a database schema.
Stuff in the real world is subject to change, so instead of only storing the provided data as you asked for, make a ledger for events. And someone submitting a forms, will be another event.
This way, you get the flexibility to verify the provided data in the future, using information that you will have in the future, but don’t have at the time the data was provided.
Of course, this is only needed if it is needed.