WITH RECURSIVE "UsersTree" AS (
SELECT
id,
email,
"parentId"
FROM "Users"
WHERE id = 3
UNION ALL
SELECT
"Users".id,
"Users".email,
"Users"."parentId"
FROM "Users"
INNER JOIN "UsersTree" ON "Users"."parentId" = "UsersTree".id
)
select * from "Cartridges" inner join "UsersTree" ON "Cartridges"."userId" = "UsersTree".id
select "Cartridges".*, SUM("Statistics"."quantityPrinted") as sum from "Cartridges"
left join "Statistics" on "Cartridges".id = "Statistics"."cartridgeId"
group by "Cartridges".id;
SELECT
"Devices".id,
"Devices".code,
"Devices".city,
"Devices".description,
"Devices"."appVersionCode",
"UsersTree".email as "userEmail",
COALESCE(SUM("Statistics"."quantityPrinted"), 0) AS "quantityPrinted",
COALESCE(JSONB_AGG(
JSON_BUILD_OBJECT(
'id', "Cartridges".id,
'code', "Cartridges".code,
'quantityResource', "Cartridges"."quantityResource",
'quantityPrinted', "Statistics"."quantityPrinted",
'lastActive', "Statistics"."lastActive"
) ORDER BY "Statistics"."lastActive" DESC
) FILTER (WHERE "Cartridges".id IS NOT NULL), '[]') AS cartridges
FROM "Devices"
LEFT JOIN "Statistics" ON "Devices".id = "Statistics"."deviceId"
LEFT JOIN "Cartridges" ON "Statistics"."cartridgeId" = "Cartridges"."id"
LEFT JOIN "UsersTree" ON "UsersTree".id = "Devices"."userId"
WHERE "UsersTree".id IS NOT NULL
OR "UsersTree".id IS NOT DISTINCT FROM ${usersTreeId}
GROUP BY "Devices".id, "UsersTree".email
ORDER BY "Devices".code
const http = require('http');
const stream = require('stream');
class ToJSON extends stream.Transform {
writableObjectMode = true;
_transform(chunk, encoding, done) {
this.push(JSON.stringify(chunk) + ',');
done();
}
}
http.createServer((request, response) => {
response.writeHead(200, {
'Content-Type': 'application/json',
'Transfer-Encoding': 'chunked'
})
const data = [{ a: 1 }, { b: 2 }, { c: 3 }, { d: 4 }, { e: 5 }];
const readable = stream.Readable.from(data, { objectMode: true });
readable
.pipe(new ToJSON({ objectMode: true }))
.pipe(response);
}).listen(8080);
/*
{
"a": 1
},
{
"b": 2
},
{
"c": 3
},
{
"d": 4
},
{
"e": 5
},
*/