-
-
Save ak-ymst/aa12a99c759996eb7cb1e78f178526db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dump | |
// 対象テーブルのレコードを全県取得する | |
// すべてのカラムのデータを文字列として扱う | |
func Dump(db *gorm.DB, tableName string) ([]map[string]sql.NullString, error) { | |
var rows, errRows = db.Raw(fmt.Sprintf("SELECT * FROM %s ", tableName)).Rows() | |
if errRows != nil { | |
return nil, errRows | |
} | |
var columns, errColumns = rows.Columns() | |
if errColumns != nil { | |
return nil, errColumns | |
} | |
var values = make([]interface{}, len(columns)) | |
for i, _ := range columns { | |
var v sql.RawBytes | |
values[i] = &v | |
} | |
var dump = []map[string]sql.NullString{} | |
for rows.Next() { | |
if errRow := rows.Scan(values...); errRow != nil { | |
return nil, errRow | |
} | |
var record = map[string]sql.NullString{} | |
for i, c := range columns { | |
if v, ok := values[i].(*sql.RawBytes); !ok { | |
return nil, fmt.Errorf("fail to convert value") | |
} else { | |
if v != nil { | |
record[c] = sql.NullString{String: string(*v), Valid: true} | |
} else { | |
record[c] = sql.NullString{String: "", Valid: false} | |
} | |
} | |
} | |
dump = append(dump, record) | |
} | |
return dump, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment