GORM: An Object Relational Mapper For Go

Introduction

Establishing A Database Connection

First of all write on terminal go get-u github.com/jinzhu/gorm and run it. Secondly write go get -u github.com/lib/pq and run it. Open main.go file and import this two link in it. On func main write db. err := gorm.Open(“postgres”, “user=gorm password=gorm dbname=gorm sslmode=disable” ) for account entering. On println write (“Connection to database established”). So we can see the result of connection.

Creating Tables

db.Createtable(&User{}) code to build a new table. With the type User struct code create a new user table. Later we can create a columns for user table. (ID uint Username string)

Creating Records

user :=User { enter columns and records in it.} At the end write fmt.Println(user) to get the result.

Querying for Records

We can write a new record in one line. User{Username: “adent”,Firstname: “Arthur”, Lastname: “Dent”}. Describe user like u :=User{} for using User column.

Updating Records

Choose the record where we want to update then write the new record and enter the db.Save(&u) code for user column update.

Deleting Records

We can do like update, choose the record for using where code and later write Delete(&User{}) code for deleting the user column.

Defining Schemas

Defining Entities

For users table we can also write like tablename: users and fields: id serial , first_name varchar(255)

Defining Tables

func (u User) TableName() string{ return “stakeholders” }

Basic Entity Creation

We can write a gorm.Model in type Users struct to enter the owner.

Customizing Field Types and Sizes

We can write on Username string line ‘sql: “type:VARCHAR(15)”’ to update the data type line. Also we can write ‘sql:”size:100"’ to size for data types.

Auto-Incrementing Field

Write in type User Struct part , Count int ‘gorm: “AUTO_INCREMENT”’ .

Transient Fields

Write on type User part TempField bool to identified to generic template field.

Unique Fields

Write on name string line ‘sql: “unique”’ code to create only the singular name or something else. Also we can write unique_index to create singular index part.

Preventing Nulls and Providing Default Values

If we want to create not null records write in string line not null code.

Primary Key Fields

We can create a UserID int and write ‘gorm:”primary_key”’ code to define user id on primary key.

Embedding Child Objects

Write for _ f := range db.NewScope(&User{}).Fields() code and also in type user struct part write on model line gorm.Model ‘gorm:”embedded”’ to embedd the child objects.

Working with Indexes

db.Model(&User{}).AddIndex(“idx_first_name”, “first_name”) code to create a new index for user. And also same code only add UniqueIndex code for last_name to create singular last name index column. If we want to delete index column we write a RemoveIndex code .

Working With Relationships

One-to-One Relationship

When we want to relation for two table eachother like user and calendar tables, we write calendar calendar and CalendarId uint on user table to relate two tables.

Foreign Key Constraints

db.Debug().Model(&Calendar{}).AddForeignKey(“user_id”, “user(id)”, “CASCADE”, “CASCADE”) to enter foreign key on user id.

One-to-Many Relationships

If we want to relation for another two table like Calendar and Appointment, we write Appts []Appointments on Calendar column and CalendarID uint on Appointment column.

Many-to-Many Relationships

If we want to relate User and Appointments tables, write on appointment column Attendees []User ‘gorm:”many2many:appointment_user”’ code to relate many to many.

Polymorphism

We have 3 columns like Cat , Dog and Toy. We relate to Cat and Dog tables on Toy table. On Cat table write Toy Toy ‘gorm: “polymorphic:owner” also write in Dog table the same codes. Then in Toy table part write OwnerID uint and OwnerType string to relate both 2 tables with Toy table.

Association API Method

db.Model(&Calendar{}).Association(“Appointments”)

.Find(&appointments) , .Append(&appointmentsToAdd) , .Delete(&appointmentsToDelete) , .Replace(&appointmentsToSubstitute) , .Count() , .Clear()

Creating, Updating , and Deleting Records

Creating Records

Write a new record for example on user table FirstName: “ Arthur”, and LastName: “Dent” and write db.Create(&u) and fmt.Println(db.Newrecord(&u))

Creating Records with Children

Insert appointments :=[]Appointment column subjects like First, Second ,Third and relate with the code on u.Appointments = appointments

Updating Records

We can update a records like db.Model(&u).Updates(“first_name”, “Alex”) and later enter the db.Save(&u) code.

Batch Updates

db.Table(“users”).Where(“last_name=?”, “Dent”).Update(“last_name”, “MacMillan-Dent”) to update lastname column to Dent.

Deleting Records

First of all we call the record where we want to delete. For this we can use db.Debug().Where(“last_name LIKE ?”, “Mac%”).Delete(&User{})

Querying the Database

Retrieving Single Records

db.Debug().FirstOrInit(&u, &User{Username: “adent”})

Retrieving Record Sets

If we want to find a record in user table db.Debug().Find(&users)

Where Clauses

We can find a records that we want. db.Debug().Where(“username =?”, “adent”).Find(&users)

Limits, Offsets, and Ordering Results

We can add limits and find the records. db.Debug().Limit(2).Find(&users).Also we can add order to desc or asc to get result by ordering.Example db.Debug().Limit(2).Order(“first_name desc”).Find(&users)

Selecting Data Subsets

db.Debug().Select([]string{“first_name”, “last_name”}).Find(&users) code for selecting first and last name and find them.

Creating Projections with Joins

If we want join 2 tables to get more results db.Debug().Model{}).Joins(“inner join calendars on calendars.user_id = users.id”) users id and calendar table be joined.

Using Row SQL

db.Debug().Exec(“SELECT * FROM users”).Find(&users) code for getting all records for users table.

Modifying Schemas

Creating New Entities

Adding Fields to an Entity

adding a new field to appointment part. db.Debug().AutoMigrate(&User{}, &Calendar{}, &Appointment{}, &Attachment{})

Adding Indexes

If we want to add a index on Calendar table add UserID line ‘sql: “index:idx_calendar_user_id”’ code .

Removing Entities

db.DropTableIfExists(“attachments”) code for removing attachment table.

Modifiying a Field’s Type

If we want to modify Firstname type on User table go to type user struct firstName string line write ‘sql:”type:VARCHAR(100)”’ code. Also add db.Debug().Model(&User{}).ModifyColumn(“first_name”, “VARCHAR(100)”). On the other hand we can use with query mode like alter function. db.Debug().Exec(‘ALTER TABLE “users” ALTER “first_name” TYPE VARCHAR(100)’)

Removing a Field

db.Debug().Model(&Appointment{}).DropColumn(“recurring”) code to drop a unwanted column.

ibrahim ÇOBANİ