0

I use ts-postgres and INSERT INTO to add new rows to my table.

import { Client } from 'ts-postgres';
let query = '...';
let res = await Client.query(query, [username, email]);

The result I get from Client.query is the following result:

Result {names: Array(0), rows: Array(0), status: "INSERT 0 1"}
Result {names: Array(0), rows: Array(0), status: "INSERT 0 0"}

In the first case 1 line got added, in the second 0. Do I really need to parse the status string in order to see how many rows got added?

2 Answers 2

2

Yep, that's something you have to deal with when working at low level (without ORM)

So here's a simple function to check for inserted rows

checkInserted(result): number {
  const status = result.status.split();
  return parseInt(status[status.length-1]);
}

you can customize it according to your requirements

Sign up to request clarification or add additional context in comments.

Comments

2
+100

It looks like the answer is yes, you really do need to parse the status string.

According to the Postgres protocol documentation, when the database finishes executing an insert command, it sends a CommandComplete message back to the client. The CommandComplete message consists of a byte that identifies the message type, a length, and a "tag," which is a string:

For an INSERT command, the tag is INSERT oid rows, where rows is the number of rows inserted. oid used to be the object ID of the inserted row if rows was 1 and the target table had OIDs, but OIDs system columns are not supported anymore; therefore oid is always 0.

That tag is the status that you are seeing. There's nothing else in the CommandComplete message.

The Node Postgres client does include a rowCount member in result, but if you look at the code, you will see that it just parses it out of the string. The Java JDBC driver also parses the string.

Comments

Your Answer

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.