Always return empty results, even if records exists

yAzou :

I used GORM.

I tried to follow example on docs.

I Have a table in MySQL DB called "Attachements"

Here is how i tried to get all records:

    type Attachements struct {
        reference int
        status int
        statusDate Timestamp
        path string
    }

func main() {

    db, err := gorm.Open(
        "mysql", 
        "root:passord@(localhost)/dwg_transformer?charset=utf8&parseTime=True&loc=Local"
    )

    if err!=nil {
        panic("Cannot connect to DB")
    }

    db.DB()
    db.DB().Ping()
    defer db.Close()

    atts := []Attachements{}

    db.Find(&atts)
    fmt.Println(atts)

}

I also tried :

    rows, err := db.Model(&Attachements{}).Rows()
    defer rows.Close()

    if err != nil {
       panic(err)
    }

    att := Attachements{}

    for rows.Next() {
       db.ScanRows(rows, &att)
       fmt.Println(att)
    }

I also tried to query by column in this way :

    db.Where(&Attachements{status: 0}).Find(&atts)

    for _, v := range atts {
    fmt.Println("reference : ", v.reference)
    fmt.Println("path : ", v.path)
    }

But in all this case I got empty output (no print, no panic, no errors !)

I tried to retrieve a list of all tables in this way :

    tables := []string{}
    db.Select(&tables, "SHOW TABLES")
    fmt.Println(tables)

it ouputs me : []

But when i check if "Attachements" table exists, it returns me true :

    check:= db.HasTable("Attachements")
    fmt.Println(check)

I can't understand what I missed (If so)... Any ideas ?

Thank you so much in advance to any GO dev wo could face what's the problem here...

Here is a screenshot of MySQL WorkBench : We can see the Attachements table and the rows

UPDATE (03/03/20 19:00):

I tried to export all the fileds as suggested in comments like this :

type Attachements struct {
    Reference int
    Status int
    StatusDate Timestamp
    Path string

   }

The results are the same : no errors for all tests, and empty outputs.

UPDATE (03/03/20 20:00):

I added a db.GetErrors(), because as suggested in comments, GORM does not reports errors automatically :

[2020-03-03 19:58:05] Error 1146: Table 'dwg_transformer.attachements' doesn't exist

Why my tables got a lowercase name?

icza :

Your last error indicates the table doesn't exist.

Quoting from GORM: Conventions: Pluralized Table Name:

Table name is the pluralized version of struct name.

type User struct {} // default table name is `users`

// Set User's table name to be `profiles`
func (User) TableName() string {
  return "profiles"
}

So GORM will use a default table name attachements for your Attachements struct. Either change the table name in your database to this, or provide a TableName() method in which you return "Attachements", e.g.:

func (Attachements) TableName() string {
   return "Attachements"
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23634&siteId=1