I have the following struct:
type TypeIncidence struct {
Number int bson:"number" json:"number"
Description string bson:"description" json:"description"
Date_time_stamp string bson:"dateTimeStamp" json:"date_time_stamp"
}
and I want insert a document in a collection:
type TypeIncidence struct {
Number int `bson:"number" json:"number"`
Description string `bson:"description" json:"description"`
Date_time_stamp **string?**
}
var incidence TypeIncidence
incidence.Number = 1
Description =" Text"
Date_time_stamp = **string?**
What data type would I have to use in a Golang structure to store date_time_struct a string?
If I want to store with the following format 'YYYY-MM-DD hh:mm:ss', what module and/or function should I use in golang? (in local machine or server converting zone time)
Thanks in advance
You can use time.Time:
CreatedAt time.Time `json:"created_at" bson:"created_at"`
However, I would recommend that you store Epoch Unix timestamp (the number of seconds since Jan 1st 1970) because it is universal:
CreatedAt int64 `json:"created_at" bson:"created_at"`
I have tried in the past to store time.Time in MongoDB through Golang but then I had trouble when I parsed the same information into a datetime object in Python. If you would like to be compatible across languages and technologies, storing the Epoch Unix timestamp would be a great option.
In my Prisma schema, I have a model that looks like this:
model Document {
id String #id #default(uuid())
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
draft Boolean #default(true)
publishedDocumentNumber Int? #unique()
text String?
}
When each document is created, it is in draft mode with the value set to true. It does not have a publishedDocumentNumber until it is officially published. When I publish a document, I will update the draft value like this:
prisma.draft.update({
where: {
id: req.body.id,
},
data: {
draft: false,
}
});
Since this document is no longer a draft, I want to safely auto-increment the publishedDocumentNumber value to the previous published document's publishedDocumentNumber value + 1. I don't want to do a prisma.document.count since I could accidentally run into a collision if two documents are publish simultaneously (race condition), and they have to be unique.
Is there a better way to safely do this?
Try using serial or smallserial as described in the documentation
This is my model:
type Event struct {
SessionId string `gorm:"type:uuid;primary_key;not null"`
Received int64 `gorm:"type:timestamp;primary_key;not null"`
EventType EventType `gorm:"primary_key;not null"`
UserId string `gorm:"type:uuid"`
GameId string
Story string
}
If I use SQLite the "Received" timestamp is stored correctly as Unix timestamp. However, with Postgres driver I get:
pq: date/time field value out of range: "1593187082040"
Turns out that type:timestamp takes time.Time and not int64. To solve the problem I had to change the field type to time.Time and also parse the timestamp. However, since the timestamp value is in "ms", parsing it in Go is a bit tricky:
time.Unix(0, 1593187082040*int64(time.Millisecond))
I have the following model...
type User struct {
ID string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
FirstName string `form:"first_name" json:"first_name,omitempty"`
LastName string `form:"last_name" json:"last_name,omitempty"`
Password string `form:"password" json:"password" bindind:"required"`
Email string `gorm:"type:varchar(110);unique_index" form:"email" json:"email,omitempty" binding:"required"`
Location string `form:"location" json:"location,omitempty"`
Avatar string `form:"avatar" json:"avatar,omitempty"`
BgImg string `form:"bg_img" json:"bg_img,omitempty"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt time.Time
}
I've tried several different ways, but this way throws (pq: relation "users" does not exist). I have no related models, it's literally just that one model.
I've tried using...
func (user *User) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("ID", uuid.NewV4())
return nil
}
Along with a uuid lib, but had no luck with that either.
Turns out I was trying to store the UUID as the wrong type, I was doing...
func (user *User) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("ID", uuid.NewV4())
return nil
}
When it needed to be...
func (user *User) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("ID", uuid.NewV4().String())
return nil
}
For postgresql, here is what I did:
go get github.com/google/uuid
Use uuid.UUID (from "github.com/google/uuid"), as type,
e.gID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"`
Add uuid-ossp extension for postgres database,
e.g
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Then, when you call DB's Create() method, the uuid is generated automatically.
Update: pg14+ gen_random_uuid()
(as mentioned in Doron Segal's comment)
pg 14 has built-in function gen_random_uuid() to generate uuid v4, e.g:
create table:
create table uuid_test (uid text default gen_random_uuid());
insert a row:
insert into uuid_test(uid) values (DEFAULT);
Then uid column is generated automatically.
Similiar, in go you can use the function as defaul value I think, e.g:
ID uuid.UUID gorm:"type:uuid;default:gen_random_uuid()"
BTW, the gen_random_uuid() function only support uuid v4 now, to use other versions, you still need uuid-ossp extension.
For this you will need gorm and go.uuid
go get github.com/jinzhu/gorm
go get github.com/satori/go.uuid
Try creating your own model base model in place of gorm.Model like so:
type Base struct {
ID string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}
You would then populate this field using a method called before creation of any record, like so:
func (base *Base) BeforeCreate(scope *gorm.Scope) error {
id, err := uuid.NewV4()
if err != nil {
return err
}
return scope.SetColumn("ID", uuid.String())
}
Therefore, for your particular case, you would have:
type User struct {
Base
FirstName string `form:"first_name" json:"first_name,omitempty"`
LastName string `form:"last_name" json:"last_name,omitempty"`
Password string `form:"password" json:"password" bindind:"required"`
Email string `gorm:"type:varchar(110);unique_index" form:"email" json:"email,omitempty" binding:"required"`
Location string `form:"location" json:"location,omitempty"`
Avatar string `form:"avatar" json:"avatar,omitempty"`
BgImg string `form:"bg_img" json:"bg_img,omitempty"`
}
More details on this can be found here
This was my solution for Gorm v1.21
go get gorm.io/gorm
go get gorm.io/driver/postgres
go get github.com/google/uuid
import (
"gorm.io/gorm"
"github.com/google/uuid"
)
type User struct {
Id: string `gorm:"primaryKey"`
}
// Note: Gorm will fail if the function signature
// does not include `*gorm.DB` and `error`
func (user *User) BeforeCreate(tx *gorm.DB) (err error) {
// UUID version 4
user.Id = uuid.NewString()
return
}
Notes:
For the Google UUID package, the methods uuid.New() and uuid.NewString() use UUID version 4. This is not clearly stated in the documentation (http://pkg.go.dev/github.com/google/uuid), but by looking into the source code, you can see that these are wrappers around uuid.NewRandom() which is stated as being UUID version 4.
While some recommend the Satori UUID package (https://github.com/satori/go.uuid), benchmarks show that it has 3.3x lower performance than the Google UUID package
(https://gist.github.com/mattes/69a4ab7027b9e8ee952b5843e7ca6955)
The error (pq: relation "users" does not exist) usually means that, the table users does not exists in the database. It has nothing to do with the relationship between two models.
So basically, You first need to create the table in the database (Or auto migrate the database As per #Apin suggest). And try to re-run the same code.
None of these worked for me using gorm v1.21.
Here was my solution. Note that I'm using the satori/go.uuid library for generating UUID, but code with google's library is near identical.
type UUIDBaseModel struct {
ID uuid.UUID `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}
func (base *UUIDBaseModel) BeforeCreate(tx *gorm.DB) error {
uuid := uuid.NewV4().String()
tx.Statement.SetColumn("ID", uuid)
return nil
}
Now I used Gorm 2.0 and this worked:
go get github.com/satori/go.uuid
type Tablename struct {
ID string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
}
Actually i have manually entered records in mysql database-using grails but i want to show the date in a coloumn in same table.
Is there any solution for this
here is my controller class
class test {
String company_name
String contact_person
Integer phone_no
String status
String place
String address
static constraints = {
company_name(nullable:false)
contact_person(nullable:false)
phone_no(uinque:true,nullable:false)
status(nullable:false)
place(nullable:false)
address( nullable:false )
}
}
Grails provides automatic timestamps via the "dateCreated" property:
Automatic timestamping
If you define a dateCreated property it will be set to the current
date for you when you create new instances. Likewise, if you define a
lastUpdated property it will be automatically be updated for you
when you change persistent instances.
(From the Grails user guide: Events and auto timestamping)
Have a look at dateCreated and lastUpdated in autoTimestamp property in GORM.