问题
I am new to Postgres database but I have choosing it for a project I am working on. I would like to add data to two tables in Postgres with one query using server-side function. After a user submit data from a form in the frontend for table2, I want my SQL query to insert id, value1 in table1. Then the same id in table one will be used to create data of table2 which will store the submitted datas. I got the code below (courtesy @ErwinBrandstetter) to create a server-side function to take parameters.
CREATE OR REPLACE FUNCTION f_my_insert(_username text
, _title text
, _description text
, _body text
, _category text
, _search_volume text
, _is_deleted bool -- type?
, _created_on timestamp) -- type?
RETURNS void AS -- or what do you want to return?
$func$
WITH ins AS (
INSERT INTO table1
(post_type, created_on)
VALUES ('keyword', now()) -- 'keyword' hard-coded, now() hard-coded, too?
RETURNING pid
)
INSERT INTO table2
(pid, author, title, description, body, category, search_volume, is_deleted, created_on)
SELECT pid, $1 , $2 , $3 , $4 , $5 , $6 , $7 , $8 -- use ordinal references
-- SELECT pid,_author,_title,_description,_body,_category,_search_volume,_is_deleted,_created_on) -- ... or parameter names
FROM ins
$func$ LANGUAGE sql;
I have 3 questions with regard to the usage of this function in my express App.
Question 1. I have a @hapi/joi data schema to validate user input. Will it affect the function as indicated above? Or better still how can I implement it with the function?
Question 2. I am thinking of using parameter $1 for table1 'now()' value and passing same for table2 created_on value. I was not sure how to go about it that's why I hard-coded it twice. Is it possible in the function code above?
Question 3. Below is my sample post request in my express App. Can I use the function inside my code? Or do I need to create a file for the function and import it into my express route code? I am not sure how to use the function above.
const keywordHandler = (req, res) => {
const values = [req.body.pid, req.body.username, req.body.title, req.body.description, req.body.body, req.body.category, req.body.search_volume, req.body.is_deleted, req.body.created_on]
pool.query(`*sample SQL query*`,
values, (k_err, k_res) => {
if (k_err) {
return console.error('Error executing query', k_err.stack)
}
res.json({
status: 'Data submitted successfully',
data: k_res.rows
});
})
};
来源:https://stackoverflow.com/questions/59193895/how-do-i-use-postgres-function-in-my-nodejs-express-app