Closed KinaneD closed 1 year ago
As it turns out this behaviour is related to the Struct's field type sql.NullFloat64
which is a struct on it's own composed on a Float64 and a Valid fields.
Related to https://github.com/gocarina/gocsv/issues/95
I think it is a common practice to export an SQL table results into a CSV, it makes sense to add support to sql Null interfaces to this package.
Finally worked my way around this by defining a proprietary type that wraps sql.NullFloat64
and implements the MarshalCSV
interface.
type NullFloat64 struct {
sql.NullFloat64
}
func (s *NullFloat64) MarshalCSV() (string, error) {
v, err := s.Value()
if v == nil {
v = 0
}
return fmt.Sprint(v), err
}
I have to manually check if value is nil
and replace it by 0
otherwise it would be added as <nil>
string to the CSV.
And changed the Model's struct definition to leverage the new type instead:
type Users struct {
ID string `gorm:"type:uuid;index;" csv:"id" fake:"{uuid}"
AudienceFemale NullFloat64 `gorm:"type:double precision;index;" csv:"audience_female" fake:"{float64range:20,100} default:null"`
Gender NullString `gorm:"type:string;default:null;size:1;index" csv:"gender" fake:"{randomstring:[m,f]}"`
}
On the other hand, large values has been added to the CSV in scientific notation i.e. 1.1259076377306024e+308
, i guess that should not be an issue.
Did the same for sql.NullString
.
Hope this helps.
Hello,
I am trying to write a slice of structs to a CSV, but some unaccounted for columns are also added and types are appended to columns titles.
Said slice is retrieved from SQL where some columns defaults to
NULL
Struct:
Based on the above struct i expect the CSV to only contain the following columns:
id
,audience_female
andgender
.gocsv.MarshalFile(&users, csvFile)
successfully writes to the CSV but the following columns:id
,audience_female.Float64
,audience_female.Valid
,gender.String
andgender.Valid
.csv:"audience_female,omitempty"
andcsv:"audience_female,default=0"
but these did not work out. 1.2. What are the supported tags? For instance see how the GORM docs document these, it would be great if these could be added to the README.0
in the case of float64?Please see the attached CSV, here's a snippet:
gocsv_duplciate_validation_columns.csv
Thank you.