PG Promise error when select then insert the data

72
December 05, 2021, at 12:00 PM

i got error on my pg-promise like this:

this is my snippet code:

// create sample payload
let samplePayload = [];
for (let index = 0; index < 10; index++) {
    samplePayload.push({
        id: uuidv1(),
    });
}
return db.task((t) => {
    samplePayload.map( sp => {
        // i want check if the id is exist on db
        let sql = `select * from sf_data where id = '${sp.id}'`;
        console.log(sql)
        const sampleBatch = t.any(sql).then(th => {
            // i want insert it if data not exists
            console.log(th);
        });
    })
    
});

i want to check if the list of data is exist in DF. If not exists, need to insert the data.

i try to fix my old code and change into this

const sfdata = await t.any('SELECT * FROM sf_data');
     const queries = sfdata.map((sp) => {
         return t.oneOrNone('select * from sf_data where id = ${id}', sp).then(result => {
             console.log(result)
            if(result){
                t.tx(async t2 => {
                    return t2.none("insert into test_sf values ($1, $2, $3)", [uuidv1(), result.id, result.sfid]);
                })
            }
         });
     });
     return t.batch(queries);

but it return error:

(node:6547) UnhandledPromiseRejectionWarning: Error: Client was closed and is not queryable at /Users/dsa/Telkom/dtp-dsa-middleware-sf/node_modules/pg/lib/client.js:570:27 at processTicksAndRejections (internal/process/task_queues.js:75:11)

any clue about this?

Answer 1

You are missing return in a few places, and your code creates a bunch of loose promises - queries that are trying to execute outside the connection, hence the error.

Here's correct code:

return db.task(t => {
    const queries = samplePayload.map(sp => {
        return t.any('select * from sf_data where id = ${id}', sp);
    })
    return t.batch(queries);
});

Better yet, this can be done with one query:

const ids = samplePayload.map(sp => sp.id);
return db.any('select * from sf_data where id in ($1)', [ids]);
READ ALSO
Kotlin Coroutine: get List of (T) from Flow&lt;sealed class &lt;list of &lt;T&gt;&gt;&gt;

Kotlin Coroutine: get List of (T) from Flow<sealed class <list of <T>>>

I have the following function that return Flow<sealed class <list of < T > > > ,

34
Ajax Search Posts and Ajax Load more

Ajax Search Posts and Ajax Load more

I'm not that yet super familiar with AJAX but I'm learning

56
Is there a Postgrest API equivalent for MySQL?

Is there a Postgrest API equivalent for MySQL?

I earlier worked on postgres sql database and created some functions there which i called using postgrest api via postman

76