I am trying to insert a row into a table defined as a model. Below is the relevant code snippets:
Package Structure:
gorm
|- server
|- insertRow.go
|- pkg
|- models
|- mytable.go
|- database
| - connectdb.go
mytable.go:
package models
type Usertable struct {
Firstname string `gorm:"column:firstname"`
Lastname string `gorm:"column:lastname"`
}
func (fmap *Usertable) TableName() string { return "usertable" }
insertRow.go
package main
import (
"fmt"
"gorm/pkg/models"
"gorm/pkg/database"
)
func main() {
params := map[string]interface{} {
"Firstname" : "MyFirstName",
"Lastname" : "LastName" ,
}
db, _ := database.NewStorage("postgres", "testdb")
var user models.Usertable
err := db.DB.Debug().Model(&user).Create(params)
if err != nil {
fmt.Println("Error :=", err)
} else {
fmt.Println("Success")
}
}
Table Definition:
testdb=# \d+ usertable
Table "public.usertable"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
-----------+------+-----------+----------+---------+----------+--------------+-------------
firstname | text | | | | extended | |
lastname | text | | | | extended | |
Executing the insertRow.go gives the following error:
(/root/gorm/cloudOps/server/testDB/insertRow.go:17)
[2023-09-23 23:51:26] pq: zero-length delimited identifier at or near """"
(/root/gorm/cloudOps/server/testDB/insertRow.go:17)
[2023-09-23 23:51:26] [0.45ms] **INSERT INTO "" DEFAULT VALUES RETURNING "".***
[0 rows affected or returned ]
Error := &{{{0 0} 0 0 {{} 0} {{} 0}} map[Firstname:MyFirstName Lastname:LastName] pq: zero-length delimited identifier at or near """" 0 0xc0000a4b60 false 2 {0xc0001a3d60} 0xc0001e8420 {{0 0} {[] {} 0xc00021cc20} map[] 0} 0xc0000a4c30 <nil> 0xc0000a2c78 false <nil>}
It seems that the tablename in the insert command is blank, please let me know what is wrong with my insert command and how to pass the right tablename to the Create call.
I tried this also with the same result:
package main
import (
"fmt"
// "gorm/pkg/models"
"gorm/pkg/database"
"gorm.io/gorm"
)
type Usertable struct {
gorm.Model
Firstname string `gorm:"column:firstname"`
Lastname string `gorm:"column:lastname"`
}
func main() {
params := map[string]interface{} {
"Firstname" : "MyFirstName",
"Lastname" : "LastName" ,
}
db, _ := database.NewStorage("postgres", "testdb")
err := db.DB.Debug().Model(&Usertable{}).Create(params)
if err != nil {
fmt.Println("Error :=", err)
} else {
fmt.Println("Success")
}
}
You set a map[string]interface{} to insert, but gorm expects to pass a struct
user := models.Usertable{
Firstname: "MyFirstName",
Lastname: "LastName",
}
result := db.DB.Debug().Create(&user)