简体   繁体   中英

Use custom function with HugSQL

I am using PostgreSQL version 10 on macOS 10.12.6 and would like to use a custom plpgsql function in a query which shall be accessible to HugSQL. The following ansatz works correctly:

-- :name do-something! :! :1
CREATE OR REPLACE FUNCTION helper()
  ... (function body of helper)
  LANGUAGE plpgsql;
INSERT INTO SomeTable (someColumn) VALUES (helper());

This works since HugSQL allows me to write multi-line SQL statements and I can include the function definition of helper() .

However, I wonder whether it's actually efficient to do so since now I am redefining the function every time the query do-something! is run. I have tried to put the function definition at the top of the input file, but it only resulted in a compiler exception.

Question: What is the best way to this?

I found a solution. Here it is for the convenience of other users of HugSQL.

The function can be defined in the migrations file that sets up the tables (I use migratus for this purpose). The scope of the function definitions is identical to the scope of the tables, so if the migration reads

CREATE OR REPLACE FUNCTION helper()
  ... (function body of helper)
  LANGUAGE plpqsql;

CREATE TABLE IF NOT EXISTS SomeTable
  (...row definitions);

then the function helper() can be used in the query posted above without having to (re-)define it prior to usage:

-- :name do-something! :! :1
INSERT INTO SomeTable (someColumn) VALUES (helper());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM