Sobes.tech
Senior

Do you use ORM or manual queries for working with the database?

sobes.tech AI

Answer from AI

In Go, both approaches — ORM and manual SQL queries — are often used depending on the task. ORM (for example, GORM) is convenient for quick prototyping and working with simple CRUD operations; it abstracts SQL and allows working with the database through structures and methods.

However, for complex queries, performance optimization, or specific operations, it is often preferable to write manual queries using the standard library database/sql or sqlx. This provides full control over SQL and can be more efficient.

Example of using GORM:

import (
    "gorm.io/gorm"
)

type User struct {
    ID   uint
    Name string
}

func getUser(db *gorm.DB, id uint) (*User, error) {
    var user User
    if err := db.First(&user, id).Error; err != nil {
        return nil, err
    }
    return &user, nil
}

Example of a manual query with database/sql:

import (
    "database/sql"
)

func getUser(db *sql.DB, id int) (*User, error) {
    user := &User{}
    err := db.QueryRow("SELECT id, name FROM users WHERE id = ?", id).Scan(&user.ID, &user.Name)
    if err != nil {
        return nil, err
    }
    return user, nil
}
Do you use ORM or manual queries for working with the… - sobes.tech