jackc / pgtype

MIT License
319 stars 112 forks source link

`pgtype.JSONB.Set` does not throw error on unsupported data types for `interface{}` fields but fails on `reflect.DeepEqual` #222

Open bohrasankalp opened 1 month ago

bohrasankalp commented 1 month ago

When attempting to use pgtype.JSONB.Set to assign interface{} data that is JSON-like (such as a map or a struct) but does not conform to JSONB’s expected format, Set completes successfully, implying compatibility. However, checking with reflect.DeepEqual reveals that the data has not been assigned correctly. The expected behavior would be for Set to return an error when encountering incompatible data structures, as this would make troubleshooting simpler and avoid silent errors in JSONB assignments.

Sample snippet

func CreatePageContent(ctx context.Context, conn *pgx.Conn, pageID int64, data interface{}) (PageContent, error) {
    QTAG := "Q_CREATE_PAGE_CONTENT"

    // Initialize JSONB object
    details := &pgtype.JSONB{}

    // Attempt to set data in JSONB
    if err := details.Set(data); err != nil {
        return PageContent{}, errors.Wrapf(err, "query error (qtag=%s)", QTAG)
    }

    // Use DeepEqual to verify
    if !reflect.DeepEqual(details, data) {
        // Expecting Set to fail, but it does not
        fmt.Printf("Set succeeded, but data was not equivalent. details: %v, data: %v\n", details, data)
    }

    return PageContent{}, nil
}

data is like {"data":"some complex string read from files, could have new line\n, tabs \t or white space character or any indefinite character, whatever possible case."}