I am building a rest api using grpc,but even though i have value populated i get the above error. The curl Post gets redirected to createAlbum method
i did create a db and table manually in postgres
my db name is album I login using psql album(no password given)
then i created
create Table PHOTO(id INTEGER PRIMARY KEY, albumId INTEGER NOT NULL, title VARCHAR(255) NOT NULL, url VARCHAR(255) UNIQUE NOT NULL, thubmNailUrl VARCHAR(255) UNIQUE NOT NULL);
This is my main code
func main(){
prosgretConname := fmt.Sprintf("dbname=%v user=%v sslmode=disable", "album", "s")
log.Infof("conname is %s", prosgretConname)
db, err := gorm.Open("postgres", prosgretConname)
if err != nil {
panic("Failed to connect to database!")
}// connects correctly to db
//db.Table("photo")
defer db.Close()
go startGRPC(db)
go startHTTP()
// Block forever
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
func startGRPC(db *gorm.DB) {
lis, err := net.Listen("tcp", "localhost:5566")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
srv := svc.NewAlbumServer(db)
albumgpb.RegisterAlbumServiceServer(grpcServer, srv)
...
}
now my newAlbumServer returns an instance of the db
type Album struct {
title string `json:"title"`
albumid int `json:"albumid"`
id int `json:"id" gorm:"primary_key;not null"`
url string `json:"url"`
thumbnailurl string `json:"thumbnailurl"`
}
func (a *AlbumServiceServer) CreateAlbum(ctx context.Context, in *albumgpb.Albumreq) (*albumgpb.Albumreq, error) {
tx := a.db.Begin()
photo := Album{}
photo.title = in.Album.Title
photo.albumid = int(in.Album.AlbumId)
photo.id = int(in.Album.Id)
photo.url = in.Album.Url
photo.thumbnailurl = in.Album.ThumbNailUrl
log.Infof("%v", photo.id) // this prints 1
log.Infof("the id is %v", int(in.Album.Id))// this prints 1 on server logs
log.Infof("%+v\n", in) //this prints the entire request in the POST command
//tx.Table("photo").
err := tx.Table("public.photo").Create(&photo).Error // fails in this line stating pq: null value in column "id" violates not-null constraint
if err != nil {
log.Errorf("could not insert into db")
tx.Rollback()
return nil, err
}
tx.Commit()
....
this is my curl request and response
curl -X POST "http://localhost:8080/album" -d '{"id":1,"albumId":2,"title":"bleh","url":"sds","thumbNailUrl":"123"}'
2020-07-17 14:34:54.641 IST [16074] ERROR: null value in column "id" violates not-null constraint
2020-07-17 14:34:54.641 IST [16074] DETAIL: Failing row contains (null, null, null, null, null).
2020-07-17 14:34:54.641 IST [16074] STATEMENT: INSERT INTO "public"."photo" DEFAULT VALUES RETURNING "public"."photo".*
{"error":"pq: null value in column \"id\" violates not-null constraint","code":2,"message":"pq: null value in column \"id\" violates not-null constraint"}
Any advice on why its failing or what wrong i am doing will really be helpull