Question

I realize "an INSERT command returns a command tag," but what's the return type of a command tag?

I.e., what should be the return type of a query language (SQL) function that ends with an INSERT?

For example:

CREATE FUNCTION messages_new(integer, integer, text) RETURNS ??? AS $$
    INSERT INTO messages (from, to, body) VALUES ($1, $2, $3);
$$ LANGUAGE SQL;

Sure, I can just specify the function's return type as integer and either add RETURNING 1 to the INSERT or SELECT 1; after the INSERT. But, I'd prefer to keep things as simple as possible.

Was it helpful?

Solution 2

Most APIs specify that DML statements return the number of records affected if there are no errors, and negative numbers as error codes if there are errors that prevent the code from executing successfully. This is a good practice to incorporate into your designs.

OTHER TIPS

If the inserted values are of any interest, as when they are processed before inserting, you can return a row of type messages:

CREATE FUNCTION messages_new(integer, integer, text) 
RETURNS messages AS $$
    INSERT INTO messages (from, to, body) VALUES ($1, $2, $3)
    returning *;
$$ LANGUAGE SQL;

And get it like this

select *
from messages_new(1,1,'text');

A return type of void works.

CREATE FUNCTION messages_new(integer, integer, text) RETURNS void AS $$
    INSERT INTO messages (from, to, body) VALUES ($1, $2, $3);
$$ LANGUAGE SQL;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top