Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use sql tags in struct in some go libs like gorm?

Tags:

sql

go

go-gorm

Well I know the necessity of tags in struct in golang and how is it accessed by reflect in golang. But I have searched and could not find a reliable answer to the question of why I should use sql tags in struct while writing struct for sql results. I have explored many sample code and people are using sql:"index" in the struct and sql:"primary_key" in the struct.

Now I have done indexing in the database layer, isn’t it enough? Should I have to use sql:"index" too get the best results? Like so I have defined primary key attribute in the database should I have to specify sql:"primary_key" as well?

My code seems to work fine without those. Just want to know their benefit and usages.

like image 496
sh0umik Avatar asked Nov 21 '15 18:11

sh0umik


People also ask

What is tag in struct Golang?

In the Go programs, you can add an optional string literal to a struct field. This is known as a struct tag. It is used to hold meta-information for a struct field. You can then export the information in the field to other packages to execute an operation or structure the data appropriately.

What are the uses of tags in Go?

In Golang, we use Tags as metadata to provide for each field in a struct. This information is made available using reflection. This is typically used by packages that transform data from one form to another. For example, we can use Tags to encode/decode JSON data or read and write from a DB.

How do you use struct tags?

To use struct tags to accomplish something, other Go code must be written to examine structs at runtime. The standard library has packages that use struct tags as part of their operation. The most popular of these is the encoding/json package.

Why is Gorm used?

GORM provides CRUD operations and can also be used for the initial migration and creation of the database schema. A few more things that GORM does well includes it's extendability with native plugin support, it's reliance on testing, and one-to-one and one-to-many group of associations.


1 Answers

I think you are referring to an ORM library like gorm

In that case, metadata like sql:"primary_key" or sql:"index" will just tell the ORM to create an index while trying to setup the tables or maybe migrate them.

A couple of examples in gorm could be: indexes, primary keys, foreign keys, many2many relations or when trying to adapt an exiting schema into your gorm models, setting the type explicitly, like for example:

type Address struct {
    ID       int
    Address1 string         `sql:"not null;unique"` // Set field as not nullable and unique
    Address2 string         `sql:"type:varchar(100);unique"`
    Post     sql.NullString `sql:"not null"`
}
like image 151
Ezequiel Moreno Avatar answered Oct 05 '22 23:10

Ezequiel Moreno