Skip to content

Commit

Permalink
fix json type
Browse files Browse the repository at this point in the history
  • Loading branch information
putuadityabayu committed Feb 10, 2024
1 parent 740ec8c commit 49de68f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 19 deletions.
1 change: 0 additions & 1 deletion string_array.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ func (d StringArray) Value() (driver.Value, error) {
}

// MarshalJSON implements json.Marshaler interface.
// Bug: Marshal undefined value
func (d StringArray) MarshalJSON() ([]byte, error) {
if !d.Present || !d.Valid {
return []byte(`null`), nil
Expand Down
34 changes: 16 additions & 18 deletions type.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,13 @@ package nullable

import (
"bytes"
"context"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"strings"

"encoding/json"

"gorm.io/datatypes"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)

Expand Down Expand Up @@ -119,15 +114,18 @@ func (Type[D]) GormDBDataType(db *gorm.DB, field *schema.Field) string {
return ""
}

func (js Type[T]) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
data, _ := js.MarshalJSON()

switch db.Dialector.Name() {
case "mysql":
if v, ok := db.Dialector.(*mysql.Dialector); ok && !strings.Contains(v.ServerVersion, "MariaDB") {
return gorm.Expr("CAST(? AS JSON)", string(data))
}
}

return gorm.Expr("?", string(data))
}
//func (js Type[T]) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
// if !js.Valid {
// return clause.Expr{SQL: "?", Vars: []any{"NULL"}, WithoutParentheses: true}
// }
//
// data, _ := js.MarshalJSON()
// switch db.Dialector.Name() {
// case "mysql":
// if v, ok := db.Dialector.(*mysql.Dialector); ok && !strings.Contains(v.ServerVersion, "MariaDB") {
// return gorm.Expr("CAST(? AS JSON)", string(data))
// }
// }
//
// return gorm.Expr("?", string(data))
//}

0 comments on commit 49de68f

Please sign in to comment.