jackc / pgx

PostgreSQL driver and toolkit for Go
MIT License
10.48k stars 828 forks source link

JSONPath Support #1506

Open theory opened 1 year ago

theory commented 1 year ago

I'm writing an application that uses JSONPath type, including arrays of JSONPaths. Looks like this type is not (yet) part of PGX, as I get this error:

 failed to encode args[0]: unable to encode []string{"$.name ?(@ == \"sparky\")"} into text format for unknown type (OID 4073): cannot find encode plan

So I tried adding it:

    for _, typeName := range []string{"jsonpath", "jsonpath[]"} {
        dataType, err := conn.Conn().LoadType(ctx, typeName)
        if err != nil {
            return nil, err
        }
        fmt.Printf("%#v", dataType)
        conn.Conn().TypeMap().RegisterType(dataType)
        fmt.Printf("TYPE %v registerd\n", typeName)
    }

Sadly this returns an error on the attempt to load jsonpath (it never gets to jsonpath[]):

array element OID not registered

I'm not sure what this mean, since jsonpath is not an array type. I presume I'm missing something bout how to register types like this.

jackc commented 1 year ago

LoadType is more for user defined types than built in types.

Try pgx as of 42d327f660c3e455e0e6668d9c269506bd586188. It doesn't support the binary format, but it should be enough to get it working for you.

theory commented 1 year ago

Thank you that does indeed fix it. Looking at 42d327f, I hadn't realized that arrays were indicated by a trailing underscore rather than []. Though this isn't a custom type, I have been known to write them, so might have use of this in the future. A bit more explanation in the types package would be helpful.