tacnode

Gorm Development Example

Tacnode supports application development using popular ORM (Object-Relational Mapping) frameworks. Gorm is an ORM tool specifically designed for the Go programming language. This article provides a quick guide to developing with Gorm.

Preparation

  1. Set up a database on Tacnode
CREATE DATABASE example;
  1. Create a table within the newly created database
CREATE TABLE customer (
    id bigint NOT NULL,
    name text NOT NULL,
    email text NOT NULL,
    create_time timestamp DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

Gorm Examples

Gorm is a solution for object-relational mapping in the Go programming language.

  1. Import Gorm dependency.
go get -u gorm.io/gorm
  1. Define a structure. Each table must correspond to a specific structure. Since we only have one customer table, we need to create a Customer structure. When defining this structure, it's important to specify how the fields map to the database columns.
type Customer struct {
    Id         int64     `gorm:"column:id;primaryKey"`
    Name       string    `gorm:"column:name;not null"`
    Email      string    `gorm:"column:email;not null"`
    CreateTime time.Time `gorm:"column:create_time;default:CURRENT_TIMESTAMP()"`
}
 
func (customer Customer) TableName() string {
    return "customer"
}
  1. Configure database connection parameters
const (
   Host     = "localhost"
   Port     = 5432
   Username = "root"
   Password = "123456"
   Database = "example"
)
  1. In the following code, we insert two new records into the customer table. Then, we query the table to confirm the insertion was successful. After that, we update one of the records and query the table again to ensure the modification has taken effect. Finally, we delete one record and run another query to verify that the deletion was successful.
func main() {
    dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", Host, Port, Username, Password, Database)
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{SkipDefaultTransaction: true})
    if err != nil {
        log.Fatal(err)
    }
 
    // Insert
    if err := Insert(db); err != nil {
        log.Fatal(err)
    }
 
    // Select
    fmt.Println("Result of the first selection:")
    if err := Select(db); err != nil {
        log.Fatal(err)
    }
 
    // Update
    if err := Update(db); err != nil {
        log.Fatal(err)
    }
 
    // Select
    fmt.Println("Result of the second selection:")
    if err := Select(db); err != nil {
        log.Fatal(err)
    }
 
    // Delete
    if err := Delete(db); err != nil {
        log.Fatal(err)
    }
 
    // Select
    fmt.Println("Result of the third selection:")
    if err := Select(db); err != nil {
        log.Fatal(err)
    }
}
 
func Insert(db *gorm.DB) error {
    tx := db.Begin()
    defer func() {
        if r := recover(); r != nil {
            tx.Rollback()
        }
    }()
 
    if err := tx.Error; err != nil {
        return err
    }
 
    firstCustomer := Customer{Id: 1, Name: "Jacob Emily", Email: "jacob.emily@tacnode.io"}
    if err := tx.Create(&firstCustomer).Error; err != nil {
        tx.Rollback()
        return err
    }
 
    secondCustomer := Customer{Id: 2, Name: "Michael Emma", Email: "michael.emma@tacnode.io"}
    if err := tx.Create(&secondCustomer).Error; err != nil {
        tx.Rollback()
        return err
    }
 
    return tx.Commit().Error
}
 
func Select(db *gorm.DB) error {
    var customers []Customer
    result := db.Find(&customers, []int{1, 2})
    if err := result.Error; err != nil {
        return err
    }
    for _, customer := range customers {
        fmt.Println(customer)
    }
    return nil
}
 
func Update(db *gorm.DB) error {
    return db.Model(&Customer{Id: 2}).Updates(&Customer{Email: "michael.emma@gmail.com"}).Error
}
 
func Delete(db *gorm.DB) error {
    return db.Delete(&Customer{Id: 1}).Error
}

The results are listed below:

Result of the first selection:
{1 Jacob Emily jacob.emily@tacnode.io 2023-10-29 00:40:16.749842 +0000 UTC}
{2 Michael Emma michael.emma@tacnode.io 2023-10-29 00:40:16.749842 +0000 UTC}
Result of the second selection:
{1 Jacob Emily jacob.emily@tacnode.io 2023-10-29 00:40:16.749842 +0000 UTC}
{2 Michael Emma michael.emma@gmail.com 2023-10-29 00:40:16.749842 +0000 UTC}
Result of the third selection:
{2 Michael Emma michael.emma@gmail.com 2023-10-29 00:40:16.749842 +0000 UTC}

On this page