After creating entry in gorm , Fetch operations fails

42 Views Asked by At

We have a scenario where we are create an entry in postgres table using gorm with below snippet

func (r *Repository) CreateUser(ctx context.Context, user *model.User) error {
       return r.db.WithContext(ctx).Create(&user).Error
}

User table has primary key as UUID which will be generated before entry creation in table . Above statement does not return any error instead we are getting UUID in return .

When i am using Fetch using same UUID in golang , I am facing record not found error . This issue seems to be an intermittent issue . Sometime it works and sometime it does not . We have validated the queries and everything seems to be correct.

Below is the snippet where we are getting user with roll_id

func (r *Repository) FetchUserByRollId(ctx context.Context, id string) (*model.User, error) {
    var user *model.User
    err := r.db.WithContext(ctx).Scopes(userRollIdScope(id)).First(&user).Error
    if err != nil {
        if errors.Is(err, gorm.ErrRecordNotFound) {
            return nil, err
        }
    }
    return user, err
}

Scope as below:


func userRollIdScope(id string) func(db *gorm.DB) *gorm.DB {
    return func(db *gorm.DB) *gorm.DB {
        return db.Where(&model.User{RollId: id})
    }
}

Even after creation , fetch fails . What could be the issue here. Tried Below way also just to be confirm that whether entry is commited or not but still facing same issue

func (r *Repository) CreateUser(ctx context.Context, user *model.User) error {
    tx := r.db.WithContext(ctx).Begin()
    defer func() {
        if r := recover(); r != nil {
            tx.Rollback()
        }
    }()
    // Perform database operation within the transaction
    if err := tx.Create(&user).Error; err != nil {
        tx.Rollback()
        return err
    }
    // Commit the transaction if there are no errors
    if err := tx.Commit().Error; err != nil {
        tx.Rollback()
        return err
    }
    return nil
}

Versions used GORM version: v1.25.1 Postgres driver Version: v1.5.2

Any suggestions?

Fetch query should return correct entry

0

There are 0 best solutions below