2

Hi I am new to golang and I am trying to insert a time.Now() value for a time.Time type of variable The weired part is that i am neither getting an error nor having the commit proccessed rather the execution of the code is been stopped when i try to insert it. Can someone please help me what should be the value that I should be trying?

db: alter table abc add column created timestamptz NULL;

struct { created time.Time db:"created" }

value been set before the insert is created = time.Now()

I expect the db to be saved with the new record

  • 2
    1) What library are you using to connect/interact with the database? 2) Have you issued an explicit `commit` after the insert? 3) To your question add(as text not image) the complete code that does the insert. – Adrian Klaver Jan 13 '23 at 18:50
  • Just a guess because I don't know how you're interacting with your database, but if the field in your struct is named `created` then it might create issues because it's not exported (starting with a capital C). – robbieperry22 Jan 13 '23 at 20:21
  • 1
    @robbieperry22 u are a real saviour been killing myself over this and ur guess is correct the capital C thing did fix my issue. (https://stackoverflow.com/questions/24837432/capitals-in-struct-fields) a new learning i'd day. not sure hwo i can upvote you though but thanks much :) – EarthsPiligrim Jan 13 '23 at 20:34
  • You're welcome! I've added my response in a separate answer, so you can accept that as the answer if you'd like :) – robbieperry22 Jan 14 '23 at 02:20
  • I use the sqlc library, which takes care of all of these kinds of issues. – Bohemian Jan 14 '23 at 02:59

1 Answers1

2

In order for any external library to be able to look at your struct fields, they need to be exported, i.e. the name must start with a capital letter.

Since your definition defines the created time with a lower case letter, only code inside your package can see that field. This is why your database interface is setting "created" to NULL - as far as it knows, no value was ever provided for that field.

type Foo struct { 
    Created time.Time db:"created"
}

Note: if you happen to be using GORM to interface with your database, it actually supports what you are trying to do by default, simply by naming the struct field CreatedAt: https://gorm.io/docs/conventions.html#CreatedAt

robbieperry22
  • 1,753
  • 1
  • 18
  • 49
  • Thank you @robbieperry22. In my case I was missing the capitalization of the C while defining my field inside my struct. As per my new learning the feild wasnt been exported lacking the capitilization im not deleting this question hoping someone like me new to golang to be benefited with it :) Cheers and Thank you. Solution credits : RobbiePerry22 A bit more detailed explanation: stackoverflow.com/questions/24837432/capitals-in-struct-fields – EarthsPiligrim Mar 30 '23 at 03:45