I'm learning to use PostgreSQL and GORM. I'm creating a struct, connecting to database, and trying to write in to database.
Source code:
db, err := gorm.Open("postgres","user=superuser password=ojcafizp123 dbname=gorm sslmode=disable")
if err != nil {
panic(err.Error())
}
defer db.Close()
database := db.DB()
err = database.Ping()
if err != nil {
panic(err.Error())
}
fmt.Println("Connection to PostgreSQL was successful!")
port := ":3000"
r := chi.NewRouter()
r.Get("/api/test",Test)
http.ListenAndServe(port, r)
}
func CreateRate (w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("postgres","user=superuser password=ojcafizp123 dbname=gorm sslmode=disable")
cure := Crypto{"BTC","USD",10000,100}
if db.NewRecord(cure) {
err = db.Create(&cure).Error
if err != nil{
panic(err.Error())
}
}
}
Struct:
type Crypto struct {
Cur1 string `json:"cur1"`
Cur2 string `json:"cur2"`
Rate float64 `json:"rate"`
Timestamp int64 `json:"timestamp"`
}
Trying to find my record in the database:
func Test (w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("postgres","user=superuser password=ojcafizp123 dbname=gorm sslmode=disable")
var testcur Crypto
db.First(&testcur)
fmt.Println(testcur)
if err != nil {
fmt.Println("No testcur detected")
}
}
But got this:
Connection to PostgreSQL was successful! { 0 0}
(/home/superuser/go/src/CryptoProject/main.go:97) [2019-07-27 05:09:10] pq: relation "cryptos" does not exist
The connection is working, but the base is still empty.
The error is saying that the table cryptos
does not currently exist, which is why the insert is not working and there's nothing in the database.
I have not previously used GORM specifically, but if it's similar to other ORMs, you would need to create a data model representing the table, and then it could create the table using that model. A quick scan of its doc shows GORM has a function called CreateTable that can be called against a Model.
You could also create the table outside of GORM using regular SQL via a tool such as psql.
Addition to @khampson, you can use AutoMigrate
feature:
type Product struct {
gorm.Model
Code string
Price uint
}
// Migrate the schema
db.AutoMigrate(&Product{})