简体   繁体   English

在HugSQL中使用自定义函数

[英]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. 我在macOS 10.12.6上使用PostgreSQL版本10,并且想在查询中使用自定义的plpgsql函数,该查询应可由HugSQL访问。 The following ansatz works correctly: 以下ansatz可以正常工作:

-- :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() . 这是可行的,因为HugSQL允许我编写多行SQL语句,并且可以包括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! 但是,我不知道这样做是否有效,因为现在我每次查询do-something!都要重新定义函数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. 在此是为了方便HugSQL的其他用户。

The function can be defined in the migrations file that sets up the tables (I use migratus for this purpose). 可以在设置表的迁移文件中定义此功能(我为此目的使用了migratus )。 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: 那么可以在上面发布的查询中使用功能helper() ,而不必在使用前(重新)定义它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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