The same rows when run a query in go program

Viewed 50

I am a newby in Go, so could someone explain what's going wrong with my code, please. I'm trying save the all table from database into struct Table

// Field
type Field struct {
    Type  string
    Value interface{}
    // Value *sql.RawBytes
}
// AddField ...
func (r *Row) addField(value interface{}) {
    type_ := fmt.Sprintf("%T", value)
    f := Field{
        type_,
        value,
    }
    *r = append(*r, f)
}

// Columns ...
type Columns []string

//Row ...
type Row []Field

// Table ...
type Table struct {
    Name string
    Columns
    Rows       []Row
    PrimaryKey []string
    ForeignKey []string
}

// GetTableData ...
func GetTableData(db *sql.DB, schemaName string, tableName string) (Table, error) {
    query := fmt.Sprintf("select * from %s.%s", schemaName, tableName)
    st, err := db.Prepare(query)
    if err != nil {
        log.Fatal(err)
        return Table{}, err
    }
    res, err := execQuery(st, tableName)
    if err != nil {
        log.Fatal(err)
        return Table{}, err
    }
    return res, nil
}

func execQuery(st *sql.Stmt, tblName string) (Table, error) {
    fmt.Printf("handle %s table\n", tblName)
    tableResult := Table{           (2)
        Name:       tblName,
        PrimaryKey: []string{},
        ForeignKey: []string{},
    }
    rows, err := st.Query()
    if err != nil {
        log.Fatal(err)
        return Table{}, err
    }
    defer rows.Close()
    cols, err := rows.Columns()
    if err != nil {
        log.Fatal(err)
        return Table{}, err
    }
    tableResult.Columns = cols
    vals := make([]interface{}, len(cols))
    for i := 0; i < len(cols); i++ {
        vals[i] = new(sql.RawBytes)
    }
    for rows.Next() {                (1)
        err = rows.Scan(vals...)
        if err != nil {
            return Table{}, err
        }
        row := Row{}
        for _, rs := range vals {
            row.addField(rs)
        }
        tableResult.Rows = append(tableResult.Rows, row)
    }
    return tableResult, nil
}

But, unfortunatelly I get the Table object with the right amount of rows, but all the rows are the similar. I've been debugging my code and noticed that on the

for rows.Next() { (1)

all old data in TableResult (2) struct overwrite by new from database

0 Answers
Related