go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.02k stars 3.94k forks source link

Gorm callbacks using raw() or native query not worked #7268

Open mftakhullaziz opened 2 weeks ago

mftakhullaziz commented 2 weeks ago

My Code

` package main

  import (
      "context"
      "fmt"
      "gorm.io/driver/postgres"
      "gorm.io/gorm"
      "log"
      "posify-service/internal/identity/infra/psql/identity_records"
  )

  func RegisterRawQueryLogger(db *gorm.DB) {
      fmt.Println("Starting raw query logger")

      db.Callback().Raw().Before("gorm:raw").Register("my_query_logger_before", func(db *gorm.DB) {
          log.Printf("Executing Query: %s", db.Statement.SQL.String())
          log.Printf("Values: %v", db.Statement.Vars)
          log.Printf("Qyert result: %v", db.Statement.Dest)
      })

      db.Callback().Raw().After("gorm:raw").Register("my_query_logger_after", func(db *gorm.DB) {
          log.Printf("Executing Query: %s", db.Statement.SQL.String())
          log.Printf("Values: %v", db.Statement.Vars)
          log.Printf("Qyert result: %v", db.Statement.Dest)
      })
  }

  func GetRoleByCode(db *gorm.DB, roleCode string, ctx context.Context) (*identity_records.RoleRecord, error) {
      var role identity_records.RoleRecord

      // Execute raw query and scan result
      if err := db.WithContext(ctx).Raw("SELECT * FROM roles WHERE role_code = ?", roleCode).Scan(&role).Error; err != nil {
          return nil, err
      }
      return &role, nil
  }

  func main() {
      // Set up database connection (PostgreSQL example DSN)
      dsn := "db connection"
      db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
      if err != nil {
          log.Fatalf("failed to connect to database: %v", err)
      }
      ctx := context.Background()

      // Register the query logger
      RegisterRawQueryLogger(db)

      // Execute the query
      role, err := GetRoleByCode(db, "MERCHANT", ctx)

      if err != nil {
          fmt.Println("Error executing query:", err)
      } else {
          fmt.Printf("Query result main: %+v\n", role)
      }
  }

`

Description

I have issue, when I want printed query result from operation native query, I registered that both raw after and before, but from both even not triggered after query operation successful, please help me how fix that

github-actions[bot] commented 2 weeks ago

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking