1

Heres my problem. I have the following tables

CREATE TABLE inventory(
 id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
 owner text NOT NULL references profile(name)
);
CREATE TABLE inventory_item(
 id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
 description text,
 amount bigint,
 inventory uuid nOT NULL references table(id)
);

Now I would like to query for a single inventory

  • all items in that inventory
  • id and owner of that inventory

So I basically get a result of the following form, to send to the client:

{
 "id":"1234123-1234-1234",
 "owner":"tom",
 "items":[
 {
 "id":"2344-123412-34",
 "description":"sword",
 "amount":33
 },
 {
 "id":"6434-123412-34",
 "description":"apple",
 "amount":23
 },
 {
 "id":"45454-1123412-34",
 "description":"bow",
 "amount":32
 },
 {
 "id":"234234-1232412-34",
 "description":"arrow",
 "amount":1
 }
 ]
}

I was thinking of querying id and owner directly and then adding the items as a subquery using ARRAY(). Unfortunately, ARRAY() only works with columns of the same type.

So how can I denormalize my table structure into a JSON array for node using a postgres query?

asked Jan 21, 2021 at 17:18
7
  • please add a minimal reproducible example to your question also take a look at dba.meta.stackexchange.com/questions/2976/… Commented Jan 21, 2021 at 17:29
  • Is there a reason that a standard ODBC return set would be inadequate? Commented Jan 21, 2021 at 17:44
  • @bbaird I would like to get the inventory info and the items in a single query Commented Jan 21, 2021 at 18:23
  • @user2741831 Why? The work done by the database will be less, even with two result sets. Seems like a solution in search of a problem. Commented Jan 21, 2021 at 18:26
  • The App runs at a different site than the DB. I've been told to minimize roundtrips. It would also be good if I could create a function that performs this task all in one. But I suppose I could try and send 2 different queries in a single request and then stich the results together in node Commented Jan 21, 2021 at 18:41

1 Answer 1

0

The answer was using json_agg instead of array_agg

answered Jan 22, 2021 at 16:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.