Reputation: 1957
We have a go app where we use Postgres as a backend DB. We use https://github.com/jmoiron/sqlx for communicating with DB. The code to read all rows from a table is as belows:
rows, err := repo.db.Queryx(ListNodesQuery)
if err != nil {
repo.logger.Log("method", "ListNodes", "error", err)
return nil, err
}
r := []*Node{}
for rows.Next() {
var n Node
err = rows.StructScan(&n)
}
After adding a new column in the DB, the code as expected errs as below
missing destination name type in *Node
as db table has more columns. Making change in code to update the struct simultaneously is ofcourse not possible.
I see that one way to turn this err off is to use db.Unsafe as documented here
Is there any other idiomatic way to deal with this situation?
Upvotes: 1
Views: 1751
Reputation: 6018
Making change in code to update the struct simultaneously is ofcourse not possible.
You can manage DB schemas inside your codebase and have some app startup code that automatically migrates DB to latest schema version to keep code and DB in sync.
One of the options is github.com/golang-migrate.
Run this code on app start to update DB schema to latest version:
migrate, err := migrate.New("folder to sql scrips", "db connection string")
if err != nil {
logger.Panic(err)
}
err = migrate.Up()
if err != nil {
logger.Panic(err)
}
Upvotes: 1