layerware / hugsql

A Clojure library for embracing SQL
https://hugsql.org
Apache License 2.0
690 stars 54 forks source link

strange key with jsonb #140

Closed Xylon2 closed 2 years ago

Xylon2 commented 2 years ago

First off, I'd like to thank the developers for this elegant framework.

I'm wanting to store JSON in postgres using the jsonb type. As an experiment, make the tables using psql:

create table playground (id serial not null primary key, imagemeta jsonb)
insert into playground (imagemeta) values ('{"bar": "baz", "balance": 7.77, "active":false}');

Now add the following in my HugSQL file:

-- :name jsonbtest :? :*
-- :doc testing jsonb with test table
select id, imagemeta->:field from playground;

Now in clojure repl:

> (db/jsonbtest {:field "balance"})
[{:id 1, :?column? 7.77}]

Why does the map I get back have such a strange key? Is this a bug?

csummers commented 2 years ago

Scratch everything from my last/deleted comment. That's the value that PG returns directly for a json path unless you give it an alias:

playground=# select id, imagemeta->'balance' from playground;
 id | ?column? 
----+----------
  1 | 7.77
(1 row)

playground=# select id, imagemeta->'balance' as balance from playground;
 id | balance 
----+---------
  1 | 7.77
(1 row)
csummers commented 2 years ago

So, if you want to specify the field as an identifier parameter type in the column alias, you could do:

select id, imagemeta->:field as :i:field from playground
Xylon2 commented 2 years ago

Ah, thankyou! So not a bug at-all then.