I am designing node + postgres web service and I need to do 3 inserts to 3 tables. Should I do 3 separate insert queries in node backend code, or implement postresql function.
Example:
insert into users(id, name, address) values (1, 'username', 'address') returning id as userid;
insert into company(id, contactPersonId, name) values (11, 1, 'Companyname) returning id as companyid;
insert into report(id, userid, companyid) values (111,1,11);
Or with a function:
create or replace function add_report_details(userid, username, address, companyid, companyname, reportid)
....
insert into users(id, name, address) values (1, 'username', 'address') returning id as userid;
insert into company(id, contactPersonId, name) values (11, 1, 'Companyname') returning id as companyid;
insert into report(id, userid, companyid) values (111,1,11);
....
Implementing this with function seems like better option, because that way I don't have to change the insert query to multiple places in code if table structure changes or I want to implement some additional features.
Is there any other benefits to use functions or is there some alternative way to handle this?
Edit: My takeaway from this is that it's better to keep insert queries in js function for readability and maintainability sake. However more complex solutions might have more relation with database, so in that case function/procedure might be preferred method.
Here are also some points to consider if you decide to use functions: How to insert data into table using stored procedures in postgresql
If you have any other suggestions or opinions about using sql functions over queries in code please comment below. I feel like this is quite common problem or that I'm not aware of limitations/best practices.
Thank you for your answers and feedback!