Skip to content
Advertisement

Problem reading uniqueidentifier from SQL response

I have tried to find the solution for this problem, but keep running my head at the wall with this one. This function is part of a Go SQL wrapper, and the function getJSON is called to extract the informations from the sql response.

The problem is, that the id parameter becomes jibberish and does not match the desired response, all the other parameters read are correct thou, so this really weirds me out.

Thank you in advance, for any attempt at figurring this problem out, it is really appreciated 🙂

func getJSON(rows *sqlx.Rows) ([]byte, error) {
    columns, err := rows.Columns()
    rawResult := make([][]byte, len(columns))
    dest := make([]interface{}, len(columns))

    for i := range rawResult {
        dest[i] = &rawResult[i]
    }

    defer rows.Close()

    var results []map[string][]byte
    for rows.Next() {
        result := make(map[string][]byte, len(columns))
        rows.Scan(dest...)
        for i, raw := range rawResult {
            if raw == nil {
                result[columns[i]] = []byte("")
            } else {
                result[columns[i]] = raw
                fmt.Println(columns[i] + " : " + string(raw))
            }
        }

        results = append(results, result)
    }
    s, err := json.Marshal(results)
    if err != nil {
        panic(err)
    }
    rows.Close()
    return s, nil
}

An example of the response, taking from the terminal:

id : r�b�X��M���+�2%
name : cat
issub : false

Expected result:

id : E262B172-B158-4DEF-8015-9BA12BF53225 
name : cat
issub : false

Advertisement

Answer

That’s not about type conversion.

An UUID (of any type; presently there are four) is defined to be a 128-bit-long lump of bytes, which is 128/8=16 bytes.
This means any bytes — not necessarily printable.

What you’re after, is a string representation of an UUID value, which

  • Separates certain groups of bytes using dashes.
  • Formats each byte in these groups using hexadecimal (base-16) representation.

Since base-16 positional count represents values 0 through 15 using a single digit (‘0’ through ‘F’), a single byte is represented by two such digits — a digit per each group of 4 bits.

I think any sensible UUID package should implement a “decoding” function/method which would produce a string representation out of those 16 bytes.
I have picked a random package produced by performing this search query, and it has github.com/google/uuid.FromBytes which produces an UUID from a given byte slice, and the type of the resulting value implements the String() method which produces what you’re after.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement